Skip to content

Commit 610a934

Browse files
Merge pull request #128 from iamsunil25/quick-sort
"quick sort in java"
2 parents 6cf3762 + 87e0a16 commit 610a934

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

Sorting/quickSort.java

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

0 commit comments

Comments
 (0)