recursive quicksort in csharp

main.cs
public static void QuickSort(int[] arr, int left, int right)
{
    if (left < right)
    {
        int pivotIndex = Partition(arr, left, right);

        QuickSort(arr, left, pivotIndex - 1);
        QuickSort(arr, pivotIndex + 1, right);
    }
}

private static int Partition(int[] arr, int left, int right)
{
    int pivot = arr[right];
    int i = left;

    for (int j = left; j < right; j++)
    {
        if (arr[j] < pivot)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
        }
    }

    int temp2 = arr[i];
    arr[i] = arr[right];
    arr[right] = temp2;

    return i;
}
652 chars
34 lines

Explanation:

  • The QuickSort method is the main entry point for the quicksort algorithm.
  • It accepts an integer array, a left index, and a right index.
  • The Partition method is called from QuickSort method, which partitions the array and returns a pivot index.
  • Recursion is used to sort the left and right parts of the array.

gistlibby LogSnag