I’ve written a QuickSort algorithm based off pseudo-code that I had been given.
I’ve been running through the outputs for about 4 hours now and I can’t seem to find exactly why my algorithm starts to derail. This sort of collection logic is something I struggle with.
Anyway, whenever I run my program there’s 3 possible results:
- The list is organized and is 100% correct.
- The list is 90% organized, one or two pairs of elements are off.
- The list is never sorted and results in an infinite loop.
Given my results it leads me to believe that something has to do with the index variable I’m using. However, I can’ figure out why or what’s wrong with it.
Here’s ALL of my code that I use for my QuickSort algorithm:
public void QuickSort(IList<int> list, int l, int r)
{
if (l>=r) return;
int index = Partition(list, l, r);
Console.WriteLine("index: " + index);
QuickSort(list, l, (index-1));
QuickSort(list, (index+1), r);
}
public int Partition(IList<int> list, int l, int r)
{
int pivot = list[l];
int i = l;
int j = r + 1;
do
{
do { i++; } while(i < list.Count && list[i] < pivot);
do { j--; } while(j > 0 && list[j] >= pivot);
Swap(list, i, j);
} while(i<j);
Swap(list, i ,j);
Swap(list, j, l);
return j;
}
public void Swap(IList<int> list, int i, int j)
{
//Console.WriteLine("Swapping [i] " + list[i] + " with [j] " + list[j]);
//PrintList(list, i, j, false);
int temp = list[i];
list[i] = list[j];
list[j] = temp;
//PrintList(list, j, i, true);
}
PrintList is simply used to test my outputs.
Here is a sample input/output:
INPUT:
[18,43,5,73,59,64,6,17,56,63]
OUTPUT: [5,6,18,17,43,59,56,63,64,73]
1 Answer