quicksort an array in csharp

main.cs
public static void QuickSort(int[] array, int left, int right) {
    if (left < right) {
        int pivotIndex = Partition(array, left, right);
        QuickSort(array, left, pivotIndex - 1);
        QuickSort(array, pivotIndex + 1, right);
    }
}

public static int Partition(int[] array, int left, int right) {
    int pivot = array[right];
    int i = left - 1;
    for (int j = left; j < right; j++) {
        if (array[j] < pivot) {
            i++;
            Swap(array, i, j);
        }
    }
    Swap(array, i + 1, right);
    return i + 1;
}

public static void Swap(int[] array, int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
682 chars
27 lines

Explanation:

The quicksort algorithm is an efficient sorting algorithm that utilizes a divide-and-conquer approach.

The QuickSort function first checks if the left index is less than the right index, as the algorithm can only sort a subarray with two or more elements. A pivot index is obtained by calling the Partition function on the current subarray. The Partition function places all elements less than a selected pivot element to its left, and all elements greater to its right, which ensures that the pivot element is sorted into its final position. The QuickSort function recursively calls itself with the left subarray and right subarray on either side of the pivot index (excluding the pivot element).

The Partition function starts by selecting the rightmost element as the pivot. The variable i is then set to the left index - 1, and a loop is created that iterates through the subarray from the left to the right index, inclusive. For each element encountered, if it is less than the pivot element, the i variable is incremented and the current element is swapped with a current element at index i. The resulting subarray has all elements less than the pivot element on its left and all elements greater on its right. Finally, the pivot element is swapped with the element at index i + 1, which places the pivot element in its final, sorted position.

gistlibby LogSnag