-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq4_quick_sort.c
67 lines (53 loc) · 1.36 KB
/
q4_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
#include <stdio.h>
#include <time.h>
void partition(int sortArr[10]){
}
int quick_sort(int sortArr[10], int strtIdx, int endIdx){ // startIndex endIndex
if(strtIdx>=endIdx)
return 0;
int i, j=strtIdx, pivot, tempVal; // i: array marker, j: swap position marker
pivot = sortArr[strtIdx]; // selects the first element as pivot
for(i=strtIdx+1;i<=endIdx;i++)
{
// if element is greater than pivot, swap them and moves marker upward.
if(pivot>=sortArr[i])
{
tempVal = sortArr[j];
sortArr[j] = sortArr[i]; // swap value
sortArr[i] = tempVal;
j++;
}
}
// if final marker is larger than the last element (pivot), swap their position.
if(sortArr[j]>sortArr[i-1])
{
tempVal = sortArr[j];
sortArr[j] = sortArr[i-1]; // swap value
sortArr[i-1] = tempVal;
}
/*printf("Sorted array:\n |");
for(i=0;i<10;i++){
printf(" %d |", sortArr[i]);
}
printf("\n\n");*/
quick_sort(sortArr, strtIdx, j-1);
quick_sort(sortArr, j+1, endIdx);
}
int main(){
int i=0, n=10, sortArr[n];
srand(time(NULL));
printf("\nRandom number:\n |");
for(i=0;i<n;i++){
sortArr[i] = rand()%1000;
printf(" %d |", sortArr[i]);
sleep(1);
}
printf("\n\n");
quick_sort(sortArr, 0, n-1);
printf("Sorted array:\n |");
for(i=0;i<n;i++){
printf(" %d |", sortArr[i]);
}
printf("\n\n");
return 0;;
}