-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick-sort.c
More file actions
82 lines (64 loc) · 1.27 KB
/
quick-sort.c
File metadata and controls
82 lines (64 loc) · 1.27 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
76
77
78
79
80
81
82
// TODO: Implement
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *gen_rand_nums(int n);
void print_nums(int *nums, int n);
void quick_sort(int *nums, int low, int high);
int main()
{
int n;
scanf("%d", &n);
int *nums = gen_rand_nums(n);
printf("Before: ");
print_nums(nums, n);
quick_sort(nums, 0, n - 1);
printf("After: ");
print_nums(nums, n);
free(nums);
}
int *gen_rand_nums(int n)
{
int *nums = (int *)calloc(n, sizeof(int));
for (int i = 0; i < n; i++)
nums[i] = 1 + rand() % 101;
return nums;
}
void print_nums(int *nums, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", nums[i]);
}
printf("\n");
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int *nums, int low, int high)
{
int pivotValue = nums[high];
int pivotIndex = low - 1;
for (int j = low; j <= high - 1; j++)
{
if (nums[j] < pivotValue)
{
pivotIndex++;
swap(&nums[pivotIndex], &nums[j]);
}
}
swap(&nums[pivotIndex + 1], &nums[high]);
return pivotIndex + 1;
}
void quick_sort(int *nums, int low, int high)
{
if (low < high)
{
int partitionIndex = partition(nums, low, high);
quick_sort(nums, low, partitionIndex - 1);
quick_sort(nums, partitionIndex + 1, high);
}
}