Skip to content

Commit b602221

Browse files
author
laileon
committed
quick sort
1 parent f038f48 commit b602221

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/com/blankj/csutom/QuickSort.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.blankj.csutom;
2+
3+
public class QuickSort {
4+
public static void main(String[] args) {
5+
int unsortedArray[] = new int[]{6, 5, 3, 1, 8, 7, 2, 4};
6+
quickSort(unsortedArray);
7+
System.out.println("After sort: ");
8+
for (int item : unsortedArray) {
9+
System.out.print(item + " ");
10+
}
11+
}
12+
13+
public static void quickSort2(int[] array, int l, int u) {
14+
for (int item : array) {
15+
System.out.print(item + " ");
16+
}
17+
System.out.println();
18+
if (l >= u) return;
19+
int pivot = array[l];
20+
int left = l + 1;
21+
int right = u;
22+
while (left <= right) {
23+
while (left <= right && array[left] < pivot) {
24+
left++;
25+
}
26+
while (left <= right && array[right] >= pivot) {
27+
right--;
28+
}
29+
if (left > right) break;
30+
// swap array[left] with array[right] while left <= right
31+
int temp = array[right];
32+
array[right] = array[left];
33+
array[left] = temp;
34+
}
35+
/* swap the smaller with pivot */
36+
int temp = array[right];
37+
array[right] = array[l];
38+
array[l] = temp;
39+
quickSort2(array, l, right - 1);
40+
quickSort2(array, right + 1, u);
41+
}
42+
43+
public static void quickSort(int[] array) {
44+
quickSort2(array, 0, array.length - 1);
45+
}
46+
}

0 commit comments

Comments
 (0)