- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
Latest commit
127 lines (63 loc) · 2.18 KB
/
Copy pathQuickSort.java
File metadata and controls
127 lines (63 loc) · 2.18 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.util.Arrays;
importjava.util.Random;
publicclassQuickSort {
// Function to partion the array on the basis of the pivot value;
staticintpartition(int[] array, intlow, inthigh) {
intj, temp, i = low + 1;
Randomrandom = newRandom();
intx = random.nextInt(high - low) + low;
temp = array[low];
array[low] = array[x];
array[x] = temp;
for (j = low + 1; j <= high; j++) {
if (array[j] <= array[low] && j != i) {
temp = array[j];
array[j] = array[i];
array[i++] = temp;
} elseif (array[j] <= array[low]) {
i++;
}
}
temp = array[i - 1];
array[i - 1] = array[low];
array[low] = temp;
returni - 1;
}
// Function to implement quick sort
staticvoidquickSort(int[] array,intlow,inthigh){
if(low<high){
intmid = partition(array,low,high);
quickSort(array,low,mid-1);
quickSort(array,mid+1,high);
}
}
// Function to read user input
publicstaticvoidmain(String[] args) {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
intsize;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exceptione) {
System.out.println("Invalid Input");
return;
}
int[] array = newint[size];
System.out.println("Enter array elements");
inti;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exceptione) {
System.out.println("An error Occurred");
}
}
System.out.println("The initial array is");
System.out.println(Arrays.toString(array));
quickSort(array,0,array.length-1);
System.out.println("The sorted array is");
System.out.println(Arrays.toString(array));
}
}