Skip to content

Commit 2c5d63a

Browse files
committed
添加快速排序递归实现
1 parent 5ccc1d5 commit 2c5d63a

File tree

1 file changed

+48
-4
lines changed

1 file changed

+48
-4
lines changed
Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,61 @@
11
package com.mistray.swapsort;
22

3+
import com.mistray.model.SortModel;
4+
35
/**
46
* @author MistLight
57
* @create 2018-11-19
6-
* @desc 快速排序
8+
* @desc 快速排序->分治算法
9+
* 逻辑:
10+
* 1.i =L; j = R; 将基准数挖出形成第一个坑a[i]
11+
* 2.j--由后向前找比它小的数,找到后挖出此数填前一个坑a[i]中
12+
* 3.i++由前向后找比它大的数,找到后也挖出此数填到前一个坑a[j]中
13+
* 4.再重复执行2,3二步,直到i==j,将基准数填入a[i]中
714
*/
815
public class QuickSort {
916
public static void main(String[] args) {
10-
11-
17+
Integer[] arr = {8, 34, 5, 92, 44, 2, 74, 12};
18+
QuickSort.quickSort(arr, 0, arr.length - 1);
19+
SortModel.show(arr);
1220
}
1321

14-
public static void quickSort(Integer[] quc){
22+
/**
23+
* 递归的方式实现快速排序
24+
*
25+
* @param arr 无序数组a
26+
*/
27+
public static void quickSort(Integer[] arr, Integer start, Integer end) {
28+
if (start < end) {
29+
int index = partition(arr, start, end);
30+
quickSort(arr, start, index - 1);
31+
quickSort(arr, index + 1, end);
32+
SortModel.show(arr);
33+
}
34+
}
1535

36+
private static int partition(Integer[] arr, Integer start, Integer end) {
37+
//arr[start]为挖的第一个坑arr[start]为8
38+
int key = arr[start];
39+
while (start < end) {
40+
// 从arr[end]开始向前找一个比arr[start]小或相等的数填到arr[end]小的数(arr[5])填到arr[start]的位置
41+
while (arr[end] >= key && end > start) {
42+
end--;
43+
}
44+
// 逆向查找找到[5]
45+
arr[start] = arr[end];
46+
// {2,34,5,92,44,2,74,12}
47+
SortModel.show(arr);
48+
// 这时又出现了一个新坑(arr[5]),从arr[start]开始向后找一个比arr[5]大的数(arr[1])填到arr[5]的位置
49+
while (arr[start] <= key && end > start) {
50+
start++;
51+
}
52+
// 正向查找找到[1]
53+
arr[end] = arr[start];
54+
SortModel.show(arr);
55+
// 所以会再次进入循环找[1]与[5]未确认的部分,直到start<end为止,将k填进对应的位置
56+
}
57+
arr[start] = key;
58+
return start;
1659
}
60+
1761
}

0 commit comments

Comments
 (0)