Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 12d5eee

Browse files
switched to Hoare partition scheme
1 parent 92455aa commit 12d5eee

File tree

1 file changed

+26
-22
lines changed

1 file changed

+26
-22
lines changed

‎src/main/java/anthonynsimon/algorithms/sorts/QuickSort.java‎

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,52 +3,56 @@
33
import java.util.Arrays;
44

55
public class QuickSort {
6-
6+
77
public void sort(int[] array) {
88
if (array.length < 2) {
99
return;
1010
}
1111

1212
quickSort(array, 0, array.length - 1);
13+
System.out.println(swaps);
1314
}
1415

1516
private void quickSort(int[] array, int min, int max) {
1617
// Base case, partition is of size one or null
17-
if (min >= max) {
18+
if (min > max) {
1819
return;
1920
}
2021

21-
// Set starting pivot at last position
22-
int pivot = max;
22+
// Reorder partition so that x < pivot on the left and x >= pivot on the right
23+
// Returned int is the index of the pivot
24+
int pivot = partition(array, min, max);
25+
26+
// Recursively apply quick sort to left and right side of list
27+
quickSort(array, min, pivot - 1);
28+
quickSort(array, pivot + 1, max);
29+
}
30+
31+
private int partition(int[] array, int min, int max) {
32+
int pivot = array[max];
2333
int left = min;
2434
int right = max;
2535

2636
// Repeat until pointers meet
27-
while (left < right) {
28-
// Continue until left side swap candidate is found
29-
while (array[left] < array[pivot]) {
37+
while (true) {
38+
// Keep moving left pointer until swap candidate is found
39+
while (array[left] < pivot) {
3040
left++;
3141
}
32-
33-
// Swap and update pivot index
34-
swap(array, left, pivot);
35-
pivot = left;
36-
37-
// Continue until right side swap candidate is found
38-
while (array[right] > array[pivot]) {
42+
// Same for right pointer
43+
while (array[right] > pivot) {
3944
right--;
4045
}
4146

42-
// Swap and update pivot index
43-
swap(array, right, pivot);
44-
pivot = right;
47+
// If pointers met, we're done on this partition, pivot is on right pointer
48+
if (left >= right) {
49+
return right;
50+
}
51+
52+
// Swap elements
53+
swap(array, left, right);
4554
}
46-
47-
// Recursively apply quick sort to left and right side of list
48-
quickSort(array, min, pivot - 1);
49-
quickSort(array, pivot + 1, max);
5055
}
51-
5256

5357
private void swap(int[] array, int a, int b) {
5458
int temp = array[a];

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /