var array = []
console.log('== 快速排序 ==\n')
console.log(`快速排序也许是最常用的排序算法了。它的复杂度为O(nlogn),且它的性能通常比其他的复
杂度为O(nlogn)的排序算法要好。和归并排序一样,快速排序也使用分治的方法,将原始数组分
为较小的数组(但它没有像归并排序那样将它们分割开)。\n`)
function createRandomArray(size) {
var arr = []
for (let i = 0; i < size; i++) {
arr.push(Math.round(Math.random() * size))
}
array = arr
return arr
}
function mergeSort() {
}
function quick(array, left, right) {
var index
if (array.length > 1) {
index = partition(array, left, right)
console.log('新下标', index)
console.log('排序 array:', array)
if (left < index - 1) {
quick(array, left, index - 1)
}
if (index < right) {
quick(array, index, right)
}
} else {
return array
}
}
function partition(array, left, right) {
var pivot = array[Math.floor((left + right) / 2)],
i = left,
j = right
console.log('主元', pivot)
while (i <= j) {
while (array[i] < pivot) {
i++
console.log('i++', i)
}
while (array[j] > pivot) {
j--
console.log('j--', j)
}
if (i < j) {
console.log('i<j111111111')
swapQuickSort(array, i, j)
i++
j--
}
}
return i
}
function swapQuickSort(array, index1, index2) {
var aux = array[index1]
array[index1] = array[index2]
array[index2] = aux
}
function quickSort() {
quick(array, 0, array.length - 1)
}
createRandomArray(9)
console.log('排序前:', array + '\n')
console.time('耗时')
quickSort()
console.timeEnd('耗时')
console.log('排序后数组:', array)