forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition_sort.c
72 lines (62 loc) · 1.25 KB
/
partition_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
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int partition(int arr[], int low, int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
while (1)
{
/* Find leftmost element >= pivot */
do
{
i++;
} while (arr[i] < pivot);
/* Find rightmost element <= pivot */
do
{
j--;
} while (arr[j] > pivot);
/* if two pointers met */
if (i >= j)
return j;
swap(&arr[i], &arr[j]);
}
}
void partitionSort(int arr[], int low, int high)
{
if (low < high)
{
int value = partition(arr, low, high);
partitionSort(arr, low, value);
partitionSort(arr, value + 1, high);
}
}
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[20];
int i, range = 100;
for (i = 0; i < 20; i++)
{
arr[i] = rand() % range + 1;
}
int size = sizeof arr / sizeof arr[0];
printf("Array: \n");
printArray(arr, size);
partitionSort(arr, 0, size - 1);
printf("Sorted Array: \n");
printArray(arr, size);
return 0;
}