Skip to content

Commit d892ea5

Browse files
committed
Quick Sort
1 parent c616315 commit d892ea5

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

bin/sortingNSearching/QuickSort.class

1.67 KB
Binary file not shown.

src/sortingNSearching/QuickSort.java

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package sortingNSearching;
2+
3+
public class QuickSort {
4+
public static void main(String[] args) {
5+
int num[] = new int[10];
6+
for (int i = 0; i < num.length; ++i) {
7+
num[i] = (int) (Math.random() * 100);
8+
}
9+
10+
// before sort
11+
System.out.println("Before sort : ");
12+
for (int i = 0; i < num.length; ++i)
13+
System.out.print(num[i] + " ");
14+
15+
System.out.println("\n after sort : ");
16+
17+
int helper[] = new int[num.length];
18+
19+
quickSort(num, 0, num.length - 1);
20+
21+
22+
23+
for (int i = 0; i < num.length; ++i)
24+
System.out.print(num[i] + " ");
25+
26+
}
27+
28+
private static void quickSort(int[] num, int low, int high) {
29+
if (low < high) {
30+
int index = partition(num, low, high);
31+
if (low < index - 1)
32+
quickSort(num, low, index - 1);// sort left half
33+
if (index < high)
34+
quickSort(num, index, high);// sort right half
35+
}
36+
37+
}
38+
39+
private static int partition(int[] num, int low, int high) {
40+
int pivot = num[low + (high - low) / 2];
41+
while (low <= high) {
42+
// find first element from left which should be on right
43+
while (num[low] < pivot)
44+
++low;
45+
46+
// find first element from right which should be on left
47+
while (num[high] > pivot)
48+
--high;
49+
50+
// swap elements and move left and right indices
51+
if (low <= high) {
52+
int temp = num[high];
53+
num[high] = num[low];
54+
num[low] = temp;
55+
++low;
56+
--high;
57+
58+
}
59+
60+
}
61+
return low;
62+
}
63+
64+
}

0 commit comments

Comments
 (0)