Algorithm - quick sort algorithm

The quick sort algorithm is famous for being "fast" and is regarded as a classic sort algorithm in the industry due to its excellent time complexity. It is also often used in interviews. If you can handwrite the quick sort algorithm during the interview, it will be a dazzling bonus. .
The quick sort algorithm is not difficult. It uses the ideas of binary search and divide and conquer to divide the boundaries of the problem and transform it into smaller problems to solve.

swift:

import Foundation

var arr = [10,9,8,7,6,4,5,3,2,1]
quickSort(array: &arr, startIndex: 0, endIndex: arr.count - 1)
print(arr)

/*
 快速排序主函数 二分查找、分治思想
 */
func quickSort (array: inout [Int], startIndex: Int, endIndex: Int) {
    
    
    if startIndex > endIndex {
    
     return }
    let mid = partition(array: &array, startIndex: startIndex, endIndex: endIndex)
    quickSort(array: &array, startIndex: startIndex, endIndex: mid - 1) //左区间分治
    quickSort(array: &array, startIndex: mid + 1, endIndex: endIndex)   //右区间分治
}

/*
 分治函数
 @return 分隔左右区间的index
 保证 arr[index] > index左边的数,arr[index] < index右边的数
 */
func partition (array: inout [Int], startIndex: Int, endIndex: Int) -> Int {
    
    
    var left = startIndex
    var right = endIndex
    let standNum = array[startIndex]    //找到基准数(也称哨兵)
    while left < right {
    
    
        //从右到左 找到第一个小于 基准数 的数
        while left < right, array[right] >= standNum {
    
    	//这里要有等号,防止排序数组中出现重复数字陷入死循环
            right -= 1
        }
        array[left] = array[right]
        
        //从左到右 找到第一个大于 基准数 的数
        while left < right, array[left] <= standNum {
    
    
            left += 1
        }
        array[right] = array[left]
    }
    array[left] = standNum
    return left
}

Print result: print result
Time complexity: O(n log(n))

Guess you like

Origin blog.csdn.net/weixin_44758107/article/details/127685900