File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ void printArray (int * arr, int size){
5
+ for (int i = 0 ; i < size; i++) cout<<arr[i]<<" " ;
6
+ cout<<endl;
7
+ }
8
+
9
+ int partition (int * arr, int start , int end){
10
+
11
+ int pivot = arr[start];
12
+ int i = start;
13
+
14
+ for (int j = start +1 ; j<= end; j++){
15
+ if (arr[j]<= pivot){
16
+ i++;
17
+ if (i != j) swap (arr[i], arr[j]);
18
+ }
19
+ }
20
+ swap (arr[start], arr[i]);
21
+
22
+ return i;
23
+
24
+ }
25
+
26
+ void quickSort (int * arr, int p, int r){
27
+ if (p < r){ // this line is important as it controls the recursion calls
28
+ int q = partition (arr, p , r);
29
+ quickSort (arr, p, q-1 );
30
+ quickSort (arr, q+1 , r);
31
+ }
32
+ }
33
+
34
+ int main (){
35
+ int n;
36
+ cout<<" enter the number of elements in the array: " <<endl;
37
+ cin>>n;
38
+
39
+ int arr[n];
40
+
41
+ cout<<" enter the elements: " <<endl;
42
+
43
+ for (int i = 0 ; i < n; i++)cin>>arr[i];
44
+
45
+ cout<<" the unsorted array is: " <<endl;
46
+ printArray (arr,n);
47
+
48
+ quickSort (arr, 0 , n-1 );
49
+
50
+ cout<<" the sorted array is: " <<endl;
51
+ printArray (arr, n);
52
+ }
You can’t perform that action at this time.
0 commit comments