I run the following code which is Insertion Sort algorithm that use binary search to find the right position of the item being inserted instead of linear search but there are two numbers in the results not sorted correctly!
#include <iostream>
using namespace std;
void insertion_sort (int a[], int n /* the size of array */)
{
int i, temp,j;
for (i = 1; i < n; i++)
{
/* Assume items before a[i] are sorted. */
/* Pick an number */
temp = a[i];
/* Do binary search to find out the
point where b is to be inserted. */
int low = 0, high = i - 1, k;
while (high-low>1)
{
int mid = (high + low) / 2;
if (temp <= a[mid])
high = mid;
else
low = mid;
}
/* Shift items between high and i by 1 */
for (k = i; k > high; k--)
a[k] = a[k - 1];
a[high] = temp;
}
}
int main()
{
int A[15]={9,5,98,2,5,4,66,12,8,54,0,11,99,55,13};
insertion_sort(A,15);
for (int i=0; i<15; i++)
cout<<A[i]<<endl;
system("pause");
return 0;
}
Output:
Why?