Quicksort in Swift

Below is an example of the Quicksort algorithm in Swift. See the Quicksort page for more information and implementations.


quicksort in Swift

func quickSort(array: inout [Int], startIndex: Int, endIndex: Int)
{
    // verify that the start and end index have not overlapped
    if (startIndex < endIndex)
    {
        // calculate the pivotIndex
        pivotIndex: Int = partition(array, startIndex, endIndex);
        // sort the left sub-array
        quickSort(array, startIndex, pivotIndex);
        // sort the right sub-array
        quickSort(array, pivotIndex + 1, endIndex);
    }
}

func partition(array: inout [Int], startIndex: Int, endIndex: Int) -> Integer
{
    pivotIndex: Int = (startIndex + endIndex) / 2;
    pivotValue: Int = array[pivotIndex];
    startIndex-=1;
    endIndex+=1;

    while (true)
    {
        // start at the FIRST index of the sub-array and increment
        // FORWARD until we find a value that is > pivotValue
        do startIndex+=1; while (array[startIndex] < pivotValue);

        // start at the LAST index of the sub-array and increment
        // BACKWARD until we find a value that is < pivotValue
        do endIndex-=1; while (array[endIndex] > pivotValue);

        if (startIndex >= endIndex) return endIndex;

        // swap values at the startIndex and endIndex
        int temp = array[startIndex];
        array[startIndex] = array[endIndex];
        array[endIndex] = temp;
    }
}

var array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
insertionSort(array: &array)
print(array)

Discussion