-
Notifications
You must be signed in to change notification settings - Fork 5
/
randomized_quick_sort.c
107 lines (87 loc) · 1.88 KB
/
randomized_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <stdlib.h>
void swap(int *, int *);
/**
* Partitioning logic.
*
* @param integer input Input array
* @param int start Start index of an array
* @param int end End index of an array
*
* @return int Partitioning pivot
*/
int partition(int *input, int start, int end)
{
int pivot = start;
for (int i = start; i < end; i++) {
if (input[i] < input[end]) {
swap(input + i, input + pivot);
pivot++;
}
}
swap(input + pivot, input + end);
return pivot;
}
/**
* Randomized partitioning logic.
*
* @param integer input Input array
* @param int start Start index of an array
* @param int end End index of an array
*
* @return int Partitioning pivot
*/
int randomized_partition(int *input, int start, int end)
{
int pivot_element_index = rand() % (end + 1 - start) + start;
swap(input + pivot_element_index, input + end);
return partition(input, start, end);
}
/**
* Quick sort algorithm.
*
* @param int input Array to sort
* @param int start Start index of an array
* @param int end End index of an array
*
* @return void
*/
void quick_sort(int *input, int start, int end)
{
if (start >= end) {
return;
}
int pivot = randomized_partition(input, start, end);
quick_sort(input, start, pivot - 1);
quick_sort(input, pivot + 1, end);
}
/**
* Swap two integers.
*
* @param int a
* @param int b
*
* @return void
*/
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
int main()
{
int n;
printf("How many numbers? ");
scanf("%d", &n);
int *input = (int *) malloc(n * sizeof(int));
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", input + i);
}
quick_sort(input, 0, n - 1);
for (int i = 0; i < n; i++) {
printf("%d\t", *(input + i));
}
free(input);
}