Skip to content

Commit d5b9065

Browse files
committed
add quick sort
1 parent 9492187 commit d5b9065

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

基础算法篇/排序算法.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#### 快速排序
2+
3+
```js
4+
var quickSort = function(arrays, start, end){
5+
if(start < end){
6+
// pivot 是分割点,pivot左边的比nums[pivot]小,右边的比nums[pivot]大
7+
let pivot = partition(arrays,start,end);
8+
quickSort(arrays,start,pivot-1);
9+
quickSort(arrays,pivot+1,end);
10+
}
11+
return arrays;
12+
}
13+
14+
var partition = function(nums, start, end){
15+
let target = nums[end];
16+
let i = start;
17+
// 将小于target移到数组前面
18+
for (let j = start; j < end; j++) {
19+
if (nums[j]<target) {
20+
swap(nums, i, j);
21+
i++;
22+
}
23+
}
24+
// 把中间的值换为用于比较的基准值
25+
swap(nums,i,end);
26+
return nums;
27+
}
28+
29+
let arrays = [72,6,57,88,60,42,83,73,48,85]
30+
console.log(quickSort(arrays,0,arrays.length-1))
31+
```
32+
33+
下面这种分治的算法较好理解,挖坑填数。
34+
35+
```js
36+
var partition = function(nums, left, right){
37+
let pivot = nums[left];
38+
while(left < right){
39+
while(left<right && nums[right]>pivot){ //从右向左找到比基准小的
40+
right--;
41+
}
42+
if (left<right) {
43+
nums[left] = nums[right]; //覆盖基准的值
44+
left++; //左指针前进一位
45+
}
46+
while(left<right && nums[left]<pivot){
47+
left++;
48+
}
49+
if (left<right) {
50+
nums[right] = nums[left];
51+
right--;
52+
}
53+
}
54+
nums[left] = pivot; //left === right
55+
return left;
56+
}
57+
```
58+

数据结构篇/栈和队列.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,7 @@ MinStack.prototype.getMin = function() {
5555
};
5656
```
5757

58+
##### 150.逆波兰表达式求值 [evaluate-reverse-polish-notation](https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/)
59+
60+
##### 133.克隆图 [clone-graph](https://leetcode-cn.com/problems/clone-graph/)
61+

0 commit comments

Comments
 (0)