-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuicksort.java
More file actions
59 lines (44 loc) · 1.54 KB
/
Quicksort.java
File metadata and controls
59 lines (44 loc) · 1.54 KB
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
import java.util.*;
public class Quicksort {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = s.nextInt();
int[] a = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
s.close();
System.out.println("Array before sorting:");
System.out.println(Arrays.toString(a));
qsort(a, 0, n - 1);
System.out.println("Array after sorting:");
System.out.println(Arrays.toString(a));
}
public static void qsort(int[] a, int first, int last) {
if (first < last) {
int pivotIndex = partition(a, first, last);
qsort(a, first, pivotIndex - 1); // Sort left partition
qsort(a, pivotIndex + 1, last); // Sort right partition
}
}
public static int partition(int[] a, int first, int last) {
int pivot = a[first]; // Choosing first element as pivot
int i = first + 1, j = last;
while (i <= j) {
while (i <= last && a[i] <= pivot) i++;
while (j >= first && a[j] > pivot) j--;
if (i < j) {
swap(a, i, j);
}
}
swap(a, first, j); // Swap pivot with the correct position
return j; // Return pivot index
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}