1
+ package io .github .gunkim .algorithm .sorting ;
2
+
3
+ public class QuickSort implements Sort {
4
+ private static final int MINIMUM_ARRAY_SIZE = 2 ;
5
+
6
+ private final int [] numbers ;
7
+ private boolean sorted = false ;
8
+
9
+ public QuickSort (int [] numbers ) {
10
+ validateInput (numbers );
11
+ this .numbers = numbers ;
12
+ }
13
+
14
+ private void validateInput (int [] numbers ) {
15
+ if (numbers == null ) {
16
+ throw new IllegalArgumentException ("Input array must not be null" );
17
+ }
18
+ if (numbers .length < MINIMUM_ARRAY_SIZE ) {
19
+ throw new IllegalArgumentException ("Input array must have at least " + MINIMUM_ARRAY_SIZE + " elements" );
20
+ }
21
+ }
22
+
23
+ @ Override
24
+ public int [] sort () {
25
+ if (sorted ) {
26
+ return numbers ;
27
+ }
28
+ quickSort (0 , numbers .length - 1 );
29
+ sorted = true ;
30
+ return numbers ;
31
+ }
32
+
33
+ private void quickSort (int start , int end ) {
34
+ if (start >= end ) {
35
+ return ;
36
+ }
37
+ int pivotIndex = partition (start , end );
38
+ quickSort (start , pivotIndex - 1 );
39
+ quickSort (pivotIndex + 1 , end );
40
+ }
41
+
42
+ private int partition (int start , int end ) {
43
+ int pivot = numbers [start ];
44
+ int leftPointer = start + 1 ;
45
+ int rightPointer = end ;
46
+
47
+ while (leftPointer <= rightPointer ) {
48
+ while (leftPointer <= end && pivot >= numbers [leftPointer ]) {
49
+ leftPointer ++;
50
+ }
51
+ while (rightPointer > start && pivot < numbers [rightPointer ]) {
52
+ rightPointer --;
53
+ }
54
+ if (leftPointer < rightPointer ) {
55
+ swap (leftPointer , rightPointer );
56
+ }
57
+ }
58
+ swap (start , rightPointer );
59
+ return rightPointer ;
60
+ }
61
+
62
+ private void swap (int i , int j ) {
63
+ int temp = numbers [i ];
64
+ numbers [i ] = numbers [j ];
65
+ numbers [j ] = temp ;
66
+ }
67
+ }
0 commit comments