Skip to content

Commit 650a9aa

Browse files
committed
Add quick sort code
1 parent 2b9b4aa commit 650a9aa

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

src/test/java/sort/QuickSort.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package sort;
2+
3+
import org.junit.Test;
4+
import utils.Utils;
5+
6+
import static org.hamcrest.CoreMatchers.is;
7+
import static org.junit.Assert.assertThat;
8+
9+
public class QuickSort {
10+
11+
/*
12+
TASK
13+
Quick sort를 구현한다.
14+
*/
15+
16+
@Test
17+
public void test() {
18+
int[] arr1 = {};
19+
int[] sortedArr1 = {};
20+
assertThat(solution(arr1, 0, arr1.length - 1), is(sortedArr1));
21+
int[] arr2 = {6,4,1,8,9,2,7,5,3};
22+
int[] sortedArr2 = {1,2,3,4,5,6,7,8,9};
23+
assertThat(solution(arr2, 0, arr2.length - 1), is(sortedArr2));
24+
int[] arr3 = {1};
25+
int[] sortedArr3 = {1};
26+
assertThat(solution(arr3, 0, arr3.length - 1), is(sortedArr3));
27+
}
28+
29+
public int[] solution(int[] arr, int left, int right) {
30+
if (arr == null) return null;
31+
32+
int[] result = arr;
33+
if (left >= right) return result;
34+
35+
int pivotPos = partition(result, left, right);
36+
37+
result = solution(result, left, pivotPos - 1);
38+
result = solution(result, pivotPos + 1, right);
39+
40+
return result;
41+
}
42+
43+
private int partition(int[] arr, int left, int right) {
44+
if (arr == null || left < 0) return -1;
45+
int pivotValue = arr[right];
46+
int endOfLowBlock = left - 1;
47+
48+
for (int pos = left; pos < right; pos++) {
49+
if (pivotValue > arr[pos]) {
50+
Utils.swapValue(arr, pos, ++endOfLowBlock);
51+
}
52+
}
53+
Utils.swapValue(arr, right, ++endOfLowBlock);
54+
55+
return endOfLowBlock;
56+
}
57+
}

0 commit comments

Comments
 (0)