mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 02:26:29 +08:00
Update quick_sort.js
Fix indentation
This commit is contained in:
parent
7eea137c28
commit
be8a586768
1 changed files with 19 additions and 19 deletions
|
@ -17,29 +17,29 @@ class QuickSort {
|
|||
partition(nums, left, right){
|
||||
// 以 nums[left] 作为基准数
|
||||
let i = left, j = right
|
||||
while(i < j){
|
||||
while(i < j && nums[j] >= nums[left]){
|
||||
j -= 1 // 从右向左找首个小于基准数的元素
|
||||
}
|
||||
while(i < j && nums[i] <= nums[left]){
|
||||
i += 1 // 从左向右找首个大于基准数的元素
|
||||
}
|
||||
// 元素交换
|
||||
this.swap(nums, i, j) // 交换这两个元素
|
||||
while(i < j){
|
||||
while(i < j && nums[j] >= nums[left]){
|
||||
j -= 1 // 从右向左找首个小于基准数的元素
|
||||
}
|
||||
this.swap(nums, i, left) // 将基准数交换至两子数组的分界线
|
||||
return i // 返回基准数的索引
|
||||
while(i < j && nums[i] <= nums[left]){
|
||||
i += 1 // 从左向右找首个大于基准数的元素
|
||||
}
|
||||
// 元素交换
|
||||
this.swap(nums, i, j) // 交换这两个元素
|
||||
}
|
||||
this.swap(nums, i, left) // 将基准数交换至两子数组的分界线
|
||||
return i // 返回基准数的索引
|
||||
}
|
||||
|
||||
/* 快速排序 */
|
||||
quickSort(nums, left, right){
|
||||
// 子数组长度为 1 时终止递归
|
||||
if(left >= right) return
|
||||
// 哨兵划分
|
||||
const pivot = this.partition(nums, left, right)
|
||||
// 递归左子数组、右子数组
|
||||
this.quickSort(nums, left, pivot - 1)
|
||||
this.quickSort(nums, pivot + 1, right)
|
||||
// 子数组长度为 1 时终止递归
|
||||
if(left >= right) return
|
||||
// 哨兵划分
|
||||
const pivot = this.partition(nums, left, right)
|
||||
// 递归左子数组、右子数组
|
||||
this.quickSort(nums, left, pivot - 1)
|
||||
this.quickSort(nums, pivot + 1, right)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue