1

I cannot find what's wrong with my insertion sort. I need to implement binary search into my sort and it will not work.

public  void insertionSort(String[] data){
    for (int i=1; i<data.length; i++){
        String item = data[i];
        int move = binarySearch(data, item, 0, i - 1);
        for (int j = i; j < move; j++){
            data[j] = data[j-1];
        }
        data[move]= item;
    }
}

public int binarySearch(String[] data, String item, int low, int high) {
    int mid;
    while(low<=high){
        mid=(low+high)/2;
        if(item.compareTo(data[mid]) > 0)
            low=mid+1;
        else if(item.compareTo(data[mid]) < 0)
            high=mid-1;
        else
            return mid;
    }
    return low;
}
2
  • Note that you could use the Arrays.binarySearch method. If it returns a negative value, just take the opposite, which is the index where the item should be if the array contained it. Commented Sep 14, 2014 at 0:51
  • The issue with the binary search part is addressed in stackoverflow.com/questions/16953009/… Commented Oct 18, 2014 at 19:52

2 Answers 2

3

Your insertion loop is wrong. Because move will always be between 0 and i (inclusive), the loop will start out with j >= move so you need to decrement j, not increment it:

for (int j = i; j > move; j--){
    data[j] = data[j-1];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Well, first off it does not seem useful to have to incorporate binary search into insertion sort. Binary search will simply find the position at which your key is located in your data array. Insertion sort, for data[i], will find the position at which it belongs before the ith index.

In your for-loop for insertion sort, you should be decrementing j instead of incrementing.

1 Comment

it is useful if you have small number of elements but complex comparison cost

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.