-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path8960 - Quick Sort.c
88 lines (73 loc) · 2.17 KB
/
8960 - Quick Sort.c
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
/**********************************************************************************************************
NAME: CANDIDA RUTH NORONHA
CLASS: SE COMPS B
ROLL NO. : 8960
BATCH: C
TITLE: QUICK SORT
SUBMISSION DATE : 22nd February, 2021
**********************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
int partition(int a[], int low, int high)
{
int x=a[low]; //pivot
int down = low;
int up = high;
int t;
while(down<up) //until the boundaries are not crossed
{
while(a[down]<=x && down<high) //if elements are smaller keep moving right(forward)
down++; //terminates when a smaller element is encountered
while(a[up]>x && up>=low) //if elements are greater keep moving left(backward)
up--; //terminates when a larger element is encountered
if(down<up) //puts a smaller element at the down position
{
//swap up and down elements
t=a[down];
a[down]=a[up];
a[up]=t;
}
}
//now pivot will occupy the position given by the end of the list of smaller elements (up)
a[low]=a[up];
a[up]=x;
return up;
}
void quick_sort(int arr[], int beg, int end)
{
int loc;
if (beg == end)
return ;
else if(beg < end)
{
loc = partition(arr, beg, end);
quick_sort(arr, beg, loc-1);
quick_sort(arr, loc+1, end);
}
}
int main()
{
int arr[SIZE], i, n;
printf("\n Enter the number of elements in the array : ");
scanf("%d",&n);
printf("\n Enter the elements of the array : ");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
quick_sort(arr, 0, n-1);
printf("\n The sorted array is :");
for(i=0;i<n;i++)
{
printf("\t%d",arr[i]);
}
printf("\n");
return 0;
}
/**********************************************************************************************************
OUTPUT :
Enter the number of elements in the array : 6
Enter the elements of the array : 27 10 36 18 25 45
The sorted array is : 10 18 25 27 36 45
**********************************************************************************************************/