0

I am reading in a list with unsorted numbers:

5 24 27 23 8 6 19

I got the binary search down, but I don't know how to use it to insert values in order. I need to change my insertInOrder method, so that the numbers are in ascending order. My method right now doesn't really do anything except print the list backwards.

static void insertInOrder( int[] arr, int cnt, int newVal )
{

    int index = -( bSearch( arr, 0, arr.length-1, newVal)) - 1;
    {
            for ( int i = cnt; i >= index+1 ; --i)
            {
                    arr[i] = arr[i-1];
            }

        arr[index] = newVal;
    }

}

public static int bSearch(int[] a, int lo, int hi, int key)
 {
    int mid = lo+(lo + hi)/2;

    if (lo <= hi) 
        return -(lo+1); 
    else if (a[mid] == key) 
        return mid;
    else if (a[mid] < key)
        return bSearch(a, mid+1, hi, key);
    else 
        return bSearch(a, lo, mid-1, key);
 }

Edit:

input: 5 24 27 23 8 6 19
current output: 19 6 8 23 27 24 5
expected output: 5 6 8 19 23 24 27
3
  • Post input, current output, and expected output, each clearly labeled as such. I think your input is 5 24 27 23 8 6 19...? Not sure though... Commented Feb 26, 2014 at 23:29
  • a binary search only works on sorted arrays, since it relies on the order of the items to know in which half to search ... Commented Feb 26, 2014 at 23:35
  • Just as a note, Java's Array class already has a <a href="docs.oracle.com/javase/7/docs/api/java/util/…, int)" title="Java's binary search">binary search</a> Commented Feb 27, 2014 at 0:16

1 Answer 1

1

Why don't use just use the Arrays class sort method?

    int myNumbers[] = {24,7,13,18,29};
    Arrays.sort(myNumbers);
    for(int i : myNumbers) {
        System.out.println(i);
    }

See docs here.

Sign up to request clarification or add additional context in comments.

2 Comments

Was going to suggest this, then computer crashed. :/ This is definitely the easiest way of doing this.
It's part of a project so I need to implement my bSearch in the insertInOrder method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.