-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathquick-sort.java
73 lines (67 loc) · 2.39 KB
/
quick-sort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class quick_sort {
public static void quickSort(int[] array, int startIndex, int endIndex) {
if (startIndex < endIndex) {
int pivot = partition(array, startIndex, endIndex);
quickSort(array, startIndex, pivot - 1);
quickSort(array, pivot + 1, endIndex);
}
}
public static int partition (int[] array, int startIndex, int endIndex) {
int pivot = array[endIndex];
int left = startIndex;
int right = endIndex - 1;
while (left <= right) {
if (array[left] <= pivot){
left++;
} else if (array[right] >= pivot){
right--;
} else{
swap(array, left, right);
}
}
swap(array, left, endIndex);
return left;
}
public static void swap(int[] array, int indexOne, int indexTwo){
int temp = array[indexOne];
array[indexOne] = array[indexTwo];
array[indexTwo] = temp;
}
public static void testingInts() {
/* This function tests quick sort on an array of 10
non repeating integers */
int[] intArray = {2, 50, 10, 31, 3, 7, 8, 1, 4, 98};
String beforeSort = "";
String afterSort = "";
for (int i = 0; i < intArray.length; i++) {
beforeSort = beforeSort + " " + intArray[i];
}
System.out.println("Before:" + beforeSort);
quickSort(intArray, 0, 9);
for (int i = 0; i < intArray.length; i++) {
afterSort = afterSort + " " + intArray[i];
}
System.out.println("After:" + afterSort);
}
public static void testingRepeats() {
/* This function tests quick sort on an array of 10
integers, some of which repeat */
int[] intArray = {10, 2, 1, 19, 8, 7, 2, 4, 76, 2};
String beforeSort = "";
String afterSort = "";
for (int i = 0; i < intArray.length; i++) {
beforeSort = beforeSort + " " + intArray[i];
}
System.out.println("Before:" + beforeSort);
quickSort(intArray, 0, 9);
for (int i = 0; i < intArray.length; i++) {
afterSort = afterSort + " " + intArray[i];
}
System.out.println("After:" + afterSort);
}
public static void main(String[] args) {
testingInts();
System.out.println(" ");
testingRepeats();
}
}