Where is my error in my binary insertion sort algorithm?
I have tried to implement binary insertion sort algorithm.
Here is my code:
public class binary_insertion {
public static void sort(int a[],int n){
for (int i=0;i<n;++i){
int temp=a[i];
int left=0;
int right=i;
while (left<right){
int middle=(left+right)/2;
if (temp>=a[middle])
left=right+1;
else
right=middle;
}
for (int j=i;j>left;--j){
swap(a,j-1,j);
}
}
}
public static void main(String[] args){
int a[]=new int[]{12,10,34,23,9,7,8,5,6};
sort(a,a.length);
for (int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
public static void swap(int a[],int i,int j){
int k=开发者_运维百科a[i];
a[i]=a[j];
a[j]=k;
}
}
and my result is wrong:
5
7
6
9
8
10
12
34
23
What did I do wrong?
First thing that stands out is here:
while (left<right){
int middle=(left+right)/2;
if (temp>=a[middle])
left=right+1;
else
right=middle;
You want left = middle + 1
.
The code works for me with that change.
Some built-in functions of java can be used here
public void sort(int array[])
{
for (int i = 1; i < array.length; i++)
{
int x = array[i];
// Find location to insert using binary search
int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1);
//Shifting array to one location right
System.arraycopy(array, j, array, j+1, i-j);
//Placing element at its correct location
array[j] = x;
}
}
public static void main(String[] args)
{
int[] arr = {37, 23, 0, 17, 12, 72, 31,
46, 100, 88, 54 };
sort(arr);
for(int i=0; i<arr.length; i++)
System.out.print(arr[i]+" ");
}
Output is:
Sorted array:
0 12 17 23 31 37 46 54 72 88 100
精彩评论