Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

  1. #1
    Junior Member
    Join Date
    Mar 2023
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    I am very new to Java and this is my first time posting here, and I need some help solving this problem. Whenever I input a number it returns the index number in the ordered array, but when certain numbers (like 62, 68, 96) are inputted, the return is either the wrong index number or an error appears in the console. This may be an easy fix but I am completely stumped, and any help would be appreciated

    import java.util.*;
    import java.lang.*;
    import java.io.*;
     
    // The main method must be in a class named "Main".
    class Main {
     
        // Literal 11 Element Array 
        static int[] _arr = {96, 61, 18, 85, 24, 62, 45, 3, 68, 57, 78};
     
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int arg = in.nextInt();
            PrintLine("Console Input: " + arg);
     
            OutputArray(_arr);
            Arrays.sort(_arr);
            OutputArray(_arr);
     
            int _cnt = _arr.length;
            int[] arr = Arrays.copyOfRange(_arr, 0, _cnt);
            int idx = BinarySearch(_arr, arg);
     
            PrintLine("Index: " + idx + "; Value: " + _arr[idx]);
        }
     
        static int BinarySearch(int[] arr, int value){
            return BinarySearch(arr, value, 0);
        }
     
        static int BinarySearch(int[] arr, int value, int idxOff){
            int len = arr.length;
            int retIdx = -1;
     
            if(len == 2){
                if(arr[0]== value){
                    retIdx = idxOff;
                } else if(arr[1] == value) {
                    retIdx = idxOff;
                }
            } else {
                int max = arr.length-1;
                int midIdx = max/2;
                System.out.println("Mid Idx: " + midIdx + "; Max Idx: " + max + "; Index Offset: " + idxOff + "; Array: " + Arrays.toString(arr));
                System.out.println("the length is: " + len);
     
                if(value == arr[midIdx]) {
                    retIdx = midIdx;
                } else {
                    if(value < arr[midIdx]){
                        int[] newArray = Arrays.copyOfRange(arr, 0, midIdx);
     
                        retIdx = BinarySearch(newArray, value);
                    } else if(arr[midIdx] < value){
                        int[] newArray = Arrays.copyOfRange(arr, midIdx, max);
                        idxOff += midIdx;
     
                        retIdx = BinarySearch(newArray, value, idxOff);
                    }
                }
            }
     
            return retIdx;
     
        }
     
        static void OutputArray(String[] arr){
            PrintLine("Array: " + Arrays.toString(arr));
        }
        static void OutputArray(int[] arr){
            PrintLine("Array: " + Arrays.toString(arr));
        }
     
        static void PrintLine(String msg){
            System.out.println(msg);
        }
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    Can you post the contents of the console that shows the problem from when you execute the program.

    One thing I see that is missing is debug print statements to show what the values of variables are as they change.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2023
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    Absolutely:

    Correct output
    3
    Console Input: 3
    Array: [96, 61, 18, 85, 24, 62, 45, 3, 68, 57, 78]
    Array: [3, 18, 24, 45, 57, 61, 62, 68, 78, 85, 96]
    Mid Idx: 5; Max Idx: 10; Index Offset: 0; Array: [3, 18, 24, 45, 57, 61, 62, 68, 78, 85, 96]
    Mid Idx: 2; Max Idx: 4; Index Offset: 0; Array: [3, 18, 24, 45, 57]
    Index: 0; Value: 3

    Wrong index
    62
    Console Input: 62
    Array: [96, 61, 18, 85, 24, 62, 45, 3, 68, 57, 78]
    Array: [3, 18, 24, 45, 57, 61, 62, 68, 78, 85, 96]
    Mid Idx: 5; Max Idx: 10; Index Offset: 0; Array: [3, 18, 24, 45, 57, 61, 62, 68, 78, 85, 96]
    Mid Idx: 2; Max Idx: 4; Index Offset: 5; Array: [61, 62, 68, 78, 85]
    Index: 0; Value: 3

    Console error
    96
    Console Input: 96
    Array: [96, 61, 18, 85, 24, 62, 45, 3, 68, 57, 78]
    Array: [3, 18, 24, 45, 57, 61, 62, 68, 78, 85, 96]
    Mid Idx: 5; Max Idx: 10; Index Offset: 0; Array: [3, 18, 24, 45, 57, 61, 62, 68, 78, 85, 96]
    Mid Idx: 2; Max Idx: 4; Index Offset: 5; Array: [61, 62, 68, 78, 85]
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at Main.main(Main.java:24)

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    Where did the -1 come from? The code needs to check the value of the index before using it with an array.

    Are there any input values that return an value other than 0?

    Have you tried to add some print statements to help with debugging the code? If you see the values in the variables it will help you see where the code is going wrong.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2023
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    Going down the list of numbers in the array, this is what they return:

    (input, index return, value return)

    3, index 0, value: 3
    18, index 1, value: 18
    24, index 2, value: 24
    45, index, 3, value: 45
    57, returns error
    61, index 5, value: 61
    62, index 0, value: 3
    68, index 2, value: 24
    78, index 8, value: 78
    85, returns error
    96, returns error

    I have tried printing some values for debugging but I am not sure what exactly I should be printing haha I am super new to Java sorry

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    what exactly I should be printing
    If you understand what the individual steps of the program are supposed to be doing, seeing if the values in the variables are the expected values will help you find the problem.


    There aren't any comments in the code so I do not know what you expect the statements in the code to do and therefore I can't look at the code to see if it is doing what you expected.

    57, returns error
    Use that input value and print out the values of the variables to see why the code does not return an index of 4.

    What is the method supposed to return if the input is not found? The code needs to test for that value and print a message instead of letting there be an error.

    this is what they return:
    ...
    18, index 1, value: 18
    I get a different result with input of 18:
    Index: 0; Value: 3
    Is the posted code the same as what you tested with?


    One thing I see is missing else statements at the end of an if/else if chain
    if(...) {
    }else if(...) {
    } <<<< HERE should be an else to catch any values that fell through the preceding tests
    Add a print statement to show what the values were that were missed.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Mar 2023
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    Sorry for cross-posting. My professor said that there was a line or multiple lines of code wrong with the original code, and said that the bulk of the original code cannot change. I have been looking and playing with different variables and stuff but I still have no idea what the solution is. The main goal is to just have the input 62 output the correct index number. I believe it has something to do with the index offset but idk what to do with that. My thought is that the index numbers are repeating and not properly adjusting to when the index offset is on the last half of the index (61, 62, 68, 78, 85, 96). I could be completely wrong but that's just my guess.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    The normal way to find bugs in a program that has bugs is to debug it. What I am suggesting is that you try debugging the code by adding more print statements that show the values of the variables as the code is executed. If you understand what the values should be, seeing the actual values should help you find the problem.
    For example what are the values of the three variables passed to the binarySearch method?
    When you print them, do they look ok?

    main goal is to just have the input 62 output the correct index number.
    Ok. start with 62, print out as many values as needed to see where the code is going wrong.

    What about the missing else after an if/else if chain? Add a print statement there so you see what values were not caught by the preceding if statements.

    My professor said that there was a line or multiple lines of code wrong
    Are you allowed to debug the code with print statements
    or must you do it with paper and pencil or just in your head?

    Bottom line: it is up to you to find the problem(s). If someone else shows you where the problem(s) are what are you learning?
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Mar 2023
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    While checking over the code and printing out different things I noticed an integer called "int value" at line 27 being used with the BinarySearch. I don't see a previous naming of int value and I was wondering what that could be. Is "value" a type of "filler" declaration or something like that for a variable?

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    I don't know where line 27 is.
    Is that the parameter to binarySearch? Look at where binarySearch is called to see what is in that variable.
    Perhaps a better name for the variable (instead of value) would be searchForMe

    Note: Java standards say that method names should start with a lowercase letter.
    BinarySearch should be binarySearch
    etc for the other method names starting with an uppercase letter
    If you don't understand my answer, don't ignore it, ask a question.

  12. #12
    Junior Member
    Join Date
    Mar 2023
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    This is the code for where "value" is being used a parameter:


    This is the first time is has been used and it was not declared before. Does it need to be declared previously or is it acceptable to be used as a parameter for a binarySearch without a declaration?
     static int binarySearch(int[] arr, int value){  //first time using value
            return binarySearch(arr, value, 0);
        }
     
        static int binarySearch(int[] arr, int value, int idxOff){
            int len = arr.length;
            int retIdx = -1;
     
            if(len == 2){
                if(arr[0]== value){
                    retIdx = idxOff;
                } else if(arr[1] == value) {
                    retIdx = idxOff+1;
                }
            } else {
                int max = arr.length-1;
                int midIdx = max/2;
                System.out.println("Mid Idx: " + midIdx + "; Max Idx: " + max + "; Index Offset: " + idxOff + "; Array: " + Arrays.toString(arr));
     
                if(value == arr[midIdx]) {
                    retIdx = midIdx;
                } else {
                    if(value < arr[midIdx]){
                        int[] newArray = Arrays.copyOfRange(arr, 0, midIdx);
     
                        retIdx = binarySearch(newArray, value);
                    } else if(arr[midIdx] < value){
                        int[] newArray = Arrays.copyOfRange(arr, midIdx, max);
                        idxOff += midIdx;
     
                        retIdx = binarySearch(newArray, value, idxOff);
                    }
                }

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Hello everybody I need some help with a homework problem dealing with arrays and binary searches

    Read this about passing arguments to a method: https://docs.oracle.com/javase/tutor...arguments.html
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Sorting arrays using a recursive binary search
    By f0rdperfect in forum Algorithms & Recursion
    Replies: 2
    Last Post: March 2nd, 2014, 09:13 PM
  2. Homework question having to do with arrays...
    By TheoAnderson in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 3rd, 2013, 12:55 PM
  3. Help with code dealing with parallel arrays.
    By danielp1213 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: November 13th, 2011, 07:43 PM
  4. My program keeps lagging when dealing with large arrays.
    By chrynelson in forum Java Theory & Questions
    Replies: 4
    Last Post: October 21st, 2011, 04:57 PM
  5. help with homework - simple arrays
    By sensoryctascale in forum Java Theory & Questions
    Replies: 3
    Last Post: April 5th, 2011, 01:39 AM