I'm trying to make a two-way insertion sort. It's supposed to take the very first value in an array, and then sort the following numbers in an array by comparing it to that first value. If the number is greater, it gets placed behind the first one in the array, if it's smaller, it is placed in front.
Here's an image that illustrates the process.
The array here is 6 5 3 1 8 7 2 4, reading from top to bottom is each step of the sorting process. It compares the number 6 with the rest of the numbers, and then places them accordingly.
So far I have this code:
void twowaysort(int n, int a[])
{
int j;
int first = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > first) {
j = i + 1;
while (j <= n - 1 && a[j] < a[j - 1]) {
swap(a[j - 1], a[j]);
j = j + 1;
}
}
if (a[i] < first) {
j = i - 1;
while (j >= 0 && a[j] > a[j + 1]) {
swap(a[j + 1], a[j]);
j = j - 1;
}
}
}
}
While this works with the array above, it seems to fail sorting the following: 13 93 58 33 58 63 11 41 87 32. This makes me believe there's an error somewhere.
Any help would be appreciated.