I found this code online while browsing around for different quicksort implementations:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Quicksort
{
class Program
{
static void Main(string[] args)
{
// Create an unsorted array of string elements
string[] unsorted = { "z","e","x","c","m","q","a"};
// Print the unsorted array
for (int i = 0; i < unsorted.Length; i++)
{
Console.Write(unsorted[i] + " ");
}
Console.WriteLine();
// Sort the array
Quicksort(unsorted, 0, unsorted.Length - 1);
// Print the sorted array
for (int i = 0; i < unsorted.Length; i++)
{
Console.Write(unsorted[i] + " ");
}
Console.WriteLine();
Console.ReadLine();
}
public static void Quicksort(IComparable[] elements, int left, int right)
{
int i = left, j = right;
IComparable pivot = elements[(left + right) / 2];
while (i <= j)
{
while (elements[i].CompareTo(pivot) < 0)
{
i++;
}
while (elements[j].CompareTo(pivot) > 0)
{
j--;
}
if (i <= j)
{
// Swap
IComparable tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
i++;
j--;
}
}
// Recursive calls
if (left < j)
{
Quicksort(elements, left, j);
}
if (i < right)
{
Quicksort(elements, i, right);
}
}
}
}
I understand how nearly all of it works but I was wondering why in the recursive calls they are using left, j and i, right for the high and low. I would think that you would want to use left, pivotIndex and pivotIndex, right. I tried this and it doesn't work but I don't really understand why. I have found a couple more in other languages that do it the same so I'm guessing it's correct (and it seems to work so that's also a good indicator that it works right). I also don't get why everyone seems to store the value of the pivot rather than the index of the pivot. If I modify this to use the index of the pivot rather than the value that also seems to work but it seems rather significant that they do this and many other implementation of quicksort do it the same way. Can someone please help me understand this?