Skip to content

Commit 5f65dde

Browse files
authored
Create example of Quicksort Algorithm in java
1 parent 9fd3485 commit 5f65dde

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Quick sort in Java
2+
3+
import java.util.Arrays;
4+
5+
class QuickSort {
6+
7+
// Function to partition the array on the basis of pivot element
8+
int partition(int array[], int low, int high) {
9+
10+
// Select the pivot element
11+
int pivot = array[high];
12+
int i = (low - 1);
13+
14+
// Put the elements smaller than pivot on the left and
15+
// greater than pivot on the right of pivot
16+
for (int j = low; j < high; j++) {
17+
if (array[j] <= pivot) {
18+
i++;
19+
int temp = array[i];
20+
array[i] = array[j];
21+
array[j] = temp;
22+
}
23+
}
24+
int temp = array[i + 1];
25+
array[i + 1] = array[high];
26+
array[high] = temp;
27+
return (i + 1);
28+
}
29+
30+
void quickSort(int array[], int low, int high) {
31+
if (low < high) {
32+
33+
// Select pivot position and put all the elements smaller
34+
// than pivot on left and greater than pivot on right
35+
int pi = partition(array, low, high);
36+
37+
// Sort the elements on the left of pivot
38+
quickSort(array, low, pi - 1);
39+
40+
// Sort the elements on the right of pivot
41+
quickSort(array, pi + 1, high);
42+
}
43+
}
44+
45+
// Driver code
46+
public static void main(String args[]) {
47+
int[] data = { 8, 7, 2, 1, 0, 9, 6 };
48+
int size = data.length;
49+
QuickSort qs = new QuickSort();
50+
qs.quickSort(data, 0, size - 1);
51+
System.out.println("Sorted Array in Ascending Order: ");
52+
System.out.println(Arrays.toString(data));
53+
}
54+
}
55+
Quicksort Complexity
56+
Time Complexities
57+
58+

0 commit comments

Comments
 (0)