forked from jaypghadiya/Java_Program
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
62 lines (56 loc) · 1.33 KB
/
Copy pathQuickSort.java
File metadata and controls
62 lines (56 loc) · 1.33 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
60
61
import java.util.Scanner;
class Sorting{
void partition(int arr[],int start,int end){
int pivot=0 ,i=0,j=0;
if(start<end) {
i=start+1;
j=end;
pivot=start;
while(i<j) {
while(arr[i]<=arr[pivot]) {
i++;
if(i>end)
break;
}
while(arr[j]>arr[pivot]) {
j--;
if(j<start)
break;
}
if(i<j) {
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
if(arr[j]<arr[pivot]) { //swap only if condition is satisfied
int temp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=temp;
}
partition(arr,start,j-1);
partition(arr,j+1,end);
}
}
void display(int array[]) {
System.out.println("The sorted elements are ");
for(int i=0;i<array.length;i++) {
System.out.print(array[i]+" ");
}
}
}
public class QuickSort {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter total number of elements");
int num_elements=sc.nextInt();
int array[]=new int[num_elements];
System.out.println("Enter array elements");
for(int i=0;i<array.length;i++) {
array[i]=sc.nextInt();
}
Sorting obj=new Sorting();
obj.partition(array, 0, array.length-1);
obj.display(array);
}
}