-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cpp
More file actions
75 lines (62 loc) · 1.55 KB
/
QuickSort.cpp
File metadata and controls
75 lines (62 loc) · 1.55 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
#include<bits/stdc++.h>
using namespace std;
void swap(int *x, int *y);
int choose_pivot(int i, int j);
void quicksort(int list[], int m, int n);
void display(int list[], const int n);
int main()
{
const int SIZE = 20;
int list[SIZE];
int i = 0;
/* generates random numbers and fill the list */
for(i = 0; i < SIZE; i++)
list[i] = rand()%200;
printf("The list before sorting is:\n");
display(list, SIZE);
/* sort the list using quicksort algorithm */
quicksort(list, 0, SIZE-1);
printf("\nThe list after sorting:\n");
display(list, SIZE);
return 0;
}
void swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
int choose_pivot(int i,int j ) {
return((i+j) /2);
}
void quicksort(int list[],int m,int n) {
int key,i,j,k;
if( m < n)
{
k = choose_pivot(m,n);
swap(&list[m],&list[k]);
key = list[m];
i = m+1;
j = n;
while(i <= j)
{
while((i <= n) && (list[i] <= key))
i++;
while((j >= m) && (list[j] > key))
j--;
if( i < j)
swap(&list[i],&list[j]);
}
/* swap two elements */
swap(&list[m],&list[j]);
/* recursively sort the lesser list */
quicksort(list,m,j-1);
quicksort(list,j+1,n);
}
}
void display(int list[],const int n) {
int i;
for(i=0; i<n; i++)
printf("%d ",list[i]);
printf("\n");
}