四谈快速排序(含尾递归)

一谈,原始的快速排序

function swap(arr, i, j) {
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}

function quickSort(arr, fromIndex, length) {
    if (length < 2) {
        return
    }
    // arr[midIndex] 的位置已经固定,不用在排
    let midIndex = partition(arr, fromIndex, length)
    let subLength = midIndex - fromIndex
    quickSort(arr, fromIndex, subLength)
    if (midIndex + 1 !== arr.length) {
        quickSort(arr, midIndex + 1, length - subLength - 1)
    }
}

function partition(arr, fromIndex, length) {
    let lastIndex = fromIndex + length - 1
    let pivot = arr[lastIndex]
    let lastIndexUnderPivot = fromIndex - 1
    for (let currentIndex = fromIndex; currentIndex < lastIndex; currentIndex++) {
        if (arr[currentIndex] <= pivot) {
            swap(arr, lastIndexUnderPivot + 1, currentIndex)
            lastIndexUnderPivot++
        }
    }
    swap(arr, lastIndexUnderPivot + 1, lastIndex)
    return lastIndexUnderPivot + 1
}

let arr = [1, 5, 2, 11, 7, 3, 1, 6, 17, 10, 312, 312, 1, 1, 2323, 4, 56, 3, 14, 5543]
quickSort(arr, 0, arr.length)
console.log(arr) // [ 1, 1, 1, 1, 2, 3, 3, 4, 5, 6, 7, 10, 11, 14, 17, 56, 312, 312, 2323, 5543 ]

二谈,优化后的快速排序

适时的采用插入排序

代码略

随机化快速排序

改变选择主元 pivot 的方式,从选择末尾的元素,改为随机选择

修改 partition 函数

function partition(arr, fromIndex, length) {
    let lastIndex = fromIndex + length - 1
    let randomIndex = fromIndex + Math.floor(Math.random() * length) // 随机索引
    swap(arr, randomIndex, lastIndex) // 与最后一个元素交换,其余不变
    let pivot = arr[lastIndex]
    let lastIndexUnderPivot = fromIndex - 1
    for (let currentIndex = fromIndex; currentIndex < lastIndex; currentIndex++) {
        if (arr[currentIndex] <= pivot) {
            swap(arr, lastIndexUnderPivot + 1, currentIndex)
            lastIndexUnderPivot++
        }
    }
    swap(arr, lastIndexUnderPivot + 1, lastIndex)
    return lastIndexUnderPivot + 1
}

三路快排

function swap(arr, i, j) {
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}

function quickSort(arr, fromIndex, length) {
    if (length < 2) {
        return
    }
    let [firstIndexEqualPivot, lastIndexEqualPivot] = partition(arr, fromIndex, length)
    // pivot 都已经排好序
    quickSort(arr, fromIndex, firstIndexEqualPivot - fromIndex)
    let subLength = fromIndex + length - 1 - (lastIndexEqualPivot + 1) + 1
    // subLength =  末尾索引 - 第一个大于主元素的索引 + 1
    quickSort(arr, lastIndexEqualPivot + 1, subLength)
}

function partition(arr, fromIndex, length) {
    let lastIndex = fromIndex + length - 1
    let randomIndex = fromIndex + Math.floor(Math.random() * length)
    swap(arr, randomIndex, lastIndex)
    let pivot = arr[lastIndex]
    let lastIndexUnderPivot = fromIndex - 1
    let firstIndexOverPivot = lastIndex
    let currentLeftIndex = fromIndex
    let currentRightIndex = lastIndex - 1
    while (currentLeftIndex <= currentRightIndex) {
        while (arr[currentLeftIndex] <= pivot) {
            if (arr[currentLeftIndex] < pivot) {
                swap(arr, lastIndexUnderPivot + 1, currentLeftIndex)
                lastIndexUnderPivot++
            }
            currentLeftIndex++
        }
        
        while (arr[currentRightIndex] >= pivot) {
            if (arr[currentRightIndex] > pivot) {
                swap(arr, firstIndexOverPivot - 1, currentRightIndex)
                firstIndexOverPivot--
            }
            currentRightIndex--
        }
        // 越界
        if (currentLeftIndex > lastIndex - 1) {
            break
        }
        // 越界
        if (currentRightIndex < fromIndex) {
            break
        }
        // 越界
        if (currentLeftIndex > currentRightIndex) {
            break
        }
        // 此时arr[currentLeftIndex] > pivot, arr[currentRightIndex] < pivot
        swap(arr, currentLeftIndex, currentRightIndex)
    }
    swap(arr, firstIndexOverPivot, lastIndex)
    let firstIndexEqualPivot = lastIndexUnderPivot + 1
    let lastIndexEqualPivot = firstIndexOverPivot
    return [firstIndexEqualPivot, lastIndexEqualPivot]
}

let arr = [1, 5, 2, 11, 7, 3, 1, 6, 17, 10]
quickSort(arr, 0, arr.length)
console.log(arr) // [ 1, 2, 3, 5, 6, 1, 7, 10, 11, 17 ]

尾递归

套路和三谈归并排序(含尾递归)中的一样,将要用但是来不及用的参数存起来,在合适的时候,再用,这里的合适一般都是计算至叶结点的时候

仅需修改 quickSort 函数如下,传入参数时,多个空数组

function quickSort(arr, fromIndex, length, argsArr) {
    if (length < 2) {
        if (argsArr.length === 0) {
            return
        }
        let args = argsArr.pop()
        return quickSort(arr, args[0], args[1], argsArr)
    }
    let [firstIndexEqualPivot, lastIndexEqualPivot] = partition(arr, fromIndex, length)
    // pivot 都已经排好序
    argsArr.push([lastIndexEqualPivot + 1, fromIndex + length - 1 - (lastIndexEqualPivot + 1) + 1])
    return quickSort(arr, fromIndex, firstIndexEqualPivot - fromIndex, argsArr)
}
...
let arr = [1, 5, 2, 11, 7, 3, 1, 6, 17, 10]
quickSort(arr, 0, arr.length, [])
console.log(arr) // [ 1, 2, 3, 5, 6, 1, 7, 10, 11, 17 ]

四谈,快速排序的应用,top-k 问题

BFPRT算法

《算法导论》9.3 最坏情况为线性时间的选择算法

输入是n个不同元素组成的数组,求第i小的元素,i从0算起

function insertSort(arr, fromIndex, length) {
    for (let currentIndex = fromIndex + 1; currentIndex < fromIndex + length; currentIndex++) {
        let currentCard = arr[currentIndex]
        let j = currentIndex - 1
        for (j; j >= fromIndex; j--) {
            if (currentCard > arr[j]) {
                break
            } else {
                arr[j + 1] = arr[j]
            }
        }
        arr[j + 1] = currentCard
    }
}

// 确定n个不同元素的数组中,第i小的元素
function BFPRT(arr, flag) {
    if (arr.length === 1) {
        return arr[0]
    }
    let medianArr = []
    for (let i = 0; i < arr.length; i = i + 5) {
        if (i + 5 > arr.length) {
            insertSort(arr, i, arr.length - i)
            if ((arr.length - i) % 2 === 0) {
                let index = (arr.length - i) / 2 + i - 1
                medianArr.push(arr[index])
            } else {
                let index = Math.floor((arr.length - i) / 2) + i
                medianArr.push(arr[index])
            }
        } else {
            insertSort(arr, i, 5)
            medianArr.push(arr[i + 2])
        }
        // 对每组元素进行插入排序,确定中位数
    }
    let subFlag = 0
    if (medianArr.length % 2 === 0) {
        subFlag = medianArr.length / 2 - 1
    } else {
        subFlag = Math.floor(medianArr.length / 2)
    }
    let pivot = BFPRT(medianArr, subFlag)
    let [leftArr, rightArr] = partition(arr, pivot)
    if (leftArr.length === flag) {
        return pivot
    }
    if (leftArr.length > flag) {
        return BFPRT(leftArr, flag)
    }
    if (leftArr.length < flag) {
        return BFPRT(rightArr, flag - leftArr.length - 1)
    }
}

function partition(arr, pivot) {
    let leftArr = []
    let rightArr = []
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < pivot) {
            leftArr.push(arr[i])
        }
        if (arr[i] > pivot) {
            rightArr.push(arr[i])
        }
    }
    return [leftArr, rightArr]
}

let arr = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 11, 13]
console.log(BFPRT(arr, 2))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Python 中实现快速排序尾递归版本相对复杂,因为 Python 的垃圾回收机制并不支持原地尾递归优化(Tail Call Optimization, TCO),这会导致递归深度过深时栈溢出。尽管如此,我们可以使用循环结构来模拟尾递归,虽然不是严格意义上的尾递归,但可以避免不必要的栈空间消耗。 快速排序通常是一个分治算法,其基本思路是选择一个基准值,将数组分为两部分,一部分所有元素都小于基准,另一部分所有元素都大于基准,然后对这两部分分别递归进行排序。然而,为了展示这种概念,这里有一个不使用递归但具有相似逻辑的非尾递归快速排序的例子: ```python def quicksort_tail_recursive(arr, low=0, high=None): if high is None: high = len(arr) - 1 while low < high: pivot_index = partition(arr, low, high) if pivot_index - low < high - pivot_index: quicksort_tail_recursive(arr, low, pivot_index - 1) else: quicksort_tail_recursive(arr, pivot_index + 1, high) return arr def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr[i+1] return i + 1 ``` 在这个版本中,`quicksort_tail_recursive` 函数使用了两个指针 `low` 和 `high` 来迭代处理数组,而不是传统的递归调用。这样可以避免栈的增长,但是Python并没有直接支持尾递归优化,所以这个实现并不能真正节省栈空间。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值