Search code examples
javasortingbinary-searchinsertion-sort

Making a binary search function


I am working on a homework task where I am supposed to make a function that will do a binary insertion sort, but my function does not seem to work properly.

Here I have tried to combine a binary search function with a insertion sort function (it is specified in the homework task that it needs to be in the form of a function: insertionSort(int[] array, int lo, int hi))

 public static void insertionSort(int[] array, int lo, int hi){
        int mid; 
        int pos; 

        for (int i = 1; i < array.length; i++) {

            int x= array[i]; 

            while (lo < hi) {
                mid = lo + (hi -lo)/2;
                if (x == array[mid]) {
                    pos = mid; 
                }
                if (x > array[mid]) {
                    lo = mid+1; 
                }
                else if (x < array[mid]) {
                    hi = mid-1; 
                }
            }
            pos = lo; 

                for (int j = i; j > pos; j--) {
                array[j] = array[j-1]; 
            }
            array[pos] = x; 
        }
    }

If I try to run it with the list {2,5,1,8,3}, the output will be

2 5 1 3 1 (if lo < hi and if lo > hi)

2 5 3 8 5 (if lo==hi)

What I am expecting though, is a sorted list... Any idea of what I am doing wrong?


Solution

  • Just to give you a possible idea:

    public static void insertionSort(int[] array) {
        if (array.length <= 1) {
            return;
        }
    
        // Start with an initially sorted part.
        int loSorted = array.length - 1;
        //int hiSorted = array.length;
    
        while (loSorted > 0) {
    
            // Take one from the array
            int x = array[0];
    
            // Where in the sorted part to insert?
            int insertI = insertPosition(array, loSorted);
    
            // Insert x at insertI
            ...
            --loSorted;
        }
    }