-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick_sort.cpp
104 lines (84 loc) · 1.44 KB
/
quick_sort.cpp
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
/* Quick Sort
Input - numbers in random order
Output - numbers sorted in ascnding or dscending order
Time Complexity - O(nLogn)
*/
#include<iostream>
using namespace std;
void swap(int *a, int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
int partition(int num[],int low ,int high)
{
int pivot=high;
int i=low-1;
for(int j=low;j<=high-1;j++)
{
if(num[j]<num[pivot])
{
i++;
swap(&num[j],&num[i]);
}
}
swap(&num[i+1],&num[pivot]);
return(i+1);
}
void quick_sort(int num[],int low,int high)
{
int pivot;
if(low<high)
{
pivot=partition(num,low,high);
quick_sort(num,low,pivot-1);
quick_sort(num,pivot+1,high);
}
}
int main()
{
int numbers[100];
int n;
int i,j,temp;
cout<<"\n Enter total number of numbers : ";
cin>>n;
cout<<"\n Enter Numbers : ";
for(int i=0;i<n;i++)
{
cin>>numbers[i];
}
cout<<"\n Your Numbers : ";
for(i=0;i<n;i++)
{
cout<<" "<<numbers[i]<<" ";
}
quick_sort(numbers,0,n-1);
cout<<"\n Your numbers in ascending order : ";
for(i=0;i<n;i++)
{
cout<<" "<<numbers[i]<<" ";
}
cout<<"\n";
return 0;
}
/* OUTPUT
(base) mansi@mansi-Vostro-15-3568:~$ c++ quick_sort.cpp
(base) mansi@mansi-Vostro-15-3568:~$ ./a.out
Enter total number of numbers : 10
Enter Numbers : 10
9
8
1
2
3
7
4
6
5
Your Numbers : 10 9 8 1 2 3 7 4 6 5
Your numbers in ascending order : 1 2 3 4 5 6 7 8 9 10
(base) mansi@mansi-Vostro-15-3568:~$ ^C
(base) mansi@mansi-Vostro-15-3568:~$
*/