【发布时间】:2020-01-02 02:00:25
【问题描述】:
我目前正在研究大学算法的理论领域,并根据我对算法工作原理的理解实现了快速排序的一个版本。之后,我将其与现有解决方案进行了比较,我的实现似乎与我发现的不同。也许有经验的人可以给我反馈:
function quicksort(array) {
let leftIndex = 0
let rightIndex = array.length - 2
if (leftIndex >= rightIndex) {
return array
}
let pivotIndex = array.length - 1
let finalPivotIndex;
do {
while (array[leftIndex] < array[pivotIndex]) {
leftIndex++
}
while (array[rightIndex] > array[pivotIndex]) {
rightIndex--
}
if (leftIndex < rightIndex) {
array = quickSwap(leftIndex, rightIndex, array)
} else {
finalPivotIndex = leftIndex
}
} while (leftIndex < rightIndex)
if (array[finalPivotIndex] > array[pivotIndex]) {
array = quickSwap(finalPivotIndex, pivotIndex, array)
}
let leftPivotArray = array.slice(0, finalPivotIndex)
let rightPivotArray = array.slice(finalPivotIndex + 1)
let sortedLeftArray = quicksort(leftPivotArray)
let sortedRightArray = quicksort(rightPivotArray)
let mergedArray = sortedLeftArray.concat([array[finalPivotIndex]])
mergedArray = mergedArray.concat(sortedRightArray)
return mergedArray
}
function quickSwap(firstIndex, secondIndex, array) {
let tmp = array[firstIndex]
array[firstIndex] = array[secondIndex]
array[secondIndex] = tmp
return array
}
【问题讨论】:
-
一个或多个索引比较应该是
leftIndex <= rightIndex。可能还有其他问题。
标签: javascript quicksort