Cycle Sort in Swift

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


cycle-sort in Swift

func cycleSort(array: inout [Int]) {
    // step 1: loop from the beginning of the array to the second to last item
    for currentIndex in 0..<(array.count - 1) {
        // step 2: save the value of the item at the currentIndex
        var item = array[currentIndex]
        // step 3: save a copy of the current index
        var currentIndexCopy = currentIndex

        // step 4: loop through all indexes that proceed the currentIndex
        for i in currentIndex + 1..<array.count {
            if (array[i] < item) {
                currentIndexCopy += 1
            }
        }

        // step 5: if currentIndexCopy has not changed, the item at the currentIndex is already in the correct position
        if (currentIndexCopy == currentIndex) {
            continue;
        }

        // step 6: skip duplicates
        while (item == array[currentIndexCopy]) {
            currentIndexCopy += 1
        }

        // step 7: swap
        var temp = array[currentIndexCopy]
        array[currentIndexCopy] = item
        item = temp

        // step 8: repeat steps 4, 6 and 7 above as long as we can find values to swap
        while (currentIndexCopy != currentIndex) {

            // step 9: save a copy of the currentIndex
            currentIndexCopy = currentIndex

            // step 10: repeat step 4
            for i in (currentIndex + 1)..<array.count {
                if array[i] < item {
                    currentIndexCopy += 1
                }
            }

            // step 10: repeat step 6
            while (item == array[currentIndexCopy]) {
                currentIndexCopy += 1
            }

            // step 10: repeat step 7
            temp = array[currentIndexCopy]
            array[currentIndexCopy] = item
            item = temp
        }
    }
}

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

Discussion