Skip to content

Commit 25bb164

Browse files
committed
快速排序
1 parent 7f09d52 commit 25bb164

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package io.github.zebinh.algorithmJava.algorithmBook.sort;
2+
3+
4+
/**
5+
* 快速排序
6+
* @author zebinh
7+
* @date 2020年4月15日 22点13分
8+
*/
9+
public class QuickSort05 {
10+
11+
12+
/**
13+
* leetcode中的模板方法
14+
* @param nums
15+
* @return
16+
*/
17+
public static int[] sortArray(int[] nums) {
18+
19+
sort(nums, 0, nums.length-1);
20+
return nums;
21+
}
22+
23+
public static void sort(int[] nums, int lo, int hi) {
24+
if (lo >= hi) {
25+
return;
26+
}
27+
int mid = partition(nums, lo, hi);
28+
sort(nums, lo, mid-1);
29+
sort(nums, mid+1, hi);
30+
}
31+
32+
public static int partition(int[] nums, int lo, int hi) {
33+
if (lo >= hi) {
34+
return lo;
35+
}
36+
int i = lo;
37+
int j = hi;
38+
int pivot = nums[hi];
39+
while(i < j) {
40+
while (nums[i] < pivot && i < j){
41+
i++;
42+
}
43+
while (nums[j] >= pivot && i < j){
44+
j--;
45+
}
46+
swap(nums, i, j);
47+
}
48+
swap(nums, i, hi);
49+
return i;
50+
}
51+
52+
/**
53+
* 交换两个数的工具方法
54+
* @param nums
55+
* @param a
56+
* @param b
57+
*/
58+
private static void swap(int[] nums, int a, int b) {
59+
int tmp = nums[a];
60+
nums[a] = nums[b];
61+
nums[b] = tmp;
62+
}
63+
64+
public static void main(String[] args) {
65+
// 测试用例
66+
int[] nums = new int[]{-1,2,-8,-10};
67+
sortArray(nums);
68+
// 打印结果
69+
for(int i = 0; i < nums.length; i++) {
70+
System.out.print(nums[i] + " ");
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)