Skip to content

Commit 82bb349

Browse files
authored
"quick sort in java"
1 parent cd3d03b commit 82bb349

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

Sorting/quickSort.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class QuickSort {
2+
public static void main(String args[]) {
3+
int arr[] = { 101, 37, 68, 29, 11, 5 };
4+
System.out.println("before sorting the array");
5+
for (int element : arr) {
6+
System.out.print(element + " ");
7+
}
8+
System.out.println();
9+
int n = arr.length;
10+
QuickSort ob = new QuickSort();
11+
ob.sort(arr, 0, n - 1);
12+
13+
System.out.println("after sorting the array");
14+
printArray(arr);
15+
}
16+
17+
// Partition Method
18+
int partition(int arr[], int lowIndex, int highIndex) {
19+
int pivot = arr[highIndex];
20+
int i = (lowIndex - 1);
21+
for (int j = lowIndex; j < highIndex; j++) {
22+
if (arr[j] <= pivot) {
23+
i++;
24+
int temp = arr[i];
25+
arr[i] = arr[j];
26+
arr[j] = temp;
27+
}
28+
}
29+
int temp = arr[i + 1];
30+
arr[i + 1] = arr[highIndex];
31+
arr[highIndex] = temp;
32+
return i + 1;
33+
}
34+
35+
void sort(int arr[], int lowIndex, int highIndex) {
36+
if (lowIndex < highIndex) {
37+
int pi = partition(arr, lowIndex, highIndex);
38+
sort(arr, lowIndex, pi - 1);
39+
sort(arr, pi + 1, highIndex);
40+
}
41+
}
42+
43+
static void printArray(int arr[]) {
44+
int n = arr.length;
45+
46+
for (int i = 0; i < n; ++i)
47+
System.out.print(arr[i] + " ");
48+
System.out.println();
49+
}
50+
}

0 commit comments

Comments
 (0)