-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksortnew.java
More file actions
55 lines (48 loc) · 1.45 KB
/
quicksortnew.java
File metadata and controls
55 lines (48 loc) · 1.45 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
import java.util.Scanner;
public class QuickSort{
public static int partition(int[] arr, int low, int high){
int pivot = arr[low], i = low, j = high, temp;
while(i < j){
while(arr[i] <= pivot && i < high){
i++;
}
while(arr[j] >= pivot && j > low){
j--;
}
if(i < j){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
}
public static void quicksort(int[] arr, int low, int high){
if(low < high){
int p = partition(arr, low, high);
quicksort(arr, low, p-1);
quicksort(arr, p+1, high);
}
}
public static void display(int[] arr, int n){
System.out.print("Sorted order: ");
for(int i=0; i<n; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = in.nextInt();
int[] arr = new int[n];
System.out.print("Enter the elements: ");
for(int i=0; i<n; i++){
arr[i] = in.nextInt();
}
quicksort(arr, 0, n-1);
display(arr, n);
}
}