TheAlgorithms-C/sorting/partition_sort.c

72 lines
1.2 KiB
C
Raw Permalink Normal View History

2019-05-04 22:53:11 +03:00
#include <stdio.h>
#include <stdlib.h>
2019-05-04 22:53:11 +03:00
2019-05-07 03:35:50 +03:00
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
2019-05-04 22:53:11 +03:00
}
2019-05-07 03:35:50 +03:00
int partition(int arr[], int low, int high)
{
int pivot = arr[low];
int i = low - 1, j = high + 1;
2019-05-04 22:53:11 +03:00
2019-05-07 03:35:50 +03:00
while (1)
{
/* Find leftmost element >= pivot */
do
{
i++;
} while (arr[i] < pivot);
2019-05-04 22:53:11 +03:00
/* Find rightmost element <= pivot */
2019-05-07 03:35:50 +03:00
do
{
j--;
} while (arr[j] > pivot);
2019-05-04 22:53:11 +03:00
2019-05-07 03:35:50 +03:00
/* if two pointers met */
if (i >= j)
return j;
2019-05-04 22:53:11 +03:00
2019-05-07 03:35:50 +03:00
swap(&arr[i], &arr[j]);
}
2019-05-04 22:53:11 +03:00
}
2019-05-07 03:35:50 +03:00
void partitionSort(int arr[], int low, int high)
{
if (low < high)
{
2019-05-04 22:53:11 +03:00
int value = partition(arr, low, high);
partitionSort(arr, low, value);
partitionSort(arr, value + 1, high);
2019-05-07 03:35:50 +03:00
}
2019-05-04 22:53:11 +03:00
}
2019-05-07 03:35:50 +03:00
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++) printf("%d ", arr[i]);
2019-05-07 03:35:50 +03:00
printf("\n");
2019-05-04 22:53:11 +03:00
}
2019-05-07 03:35:50 +03:00
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;
2019-05-04 22:53:11 +03:00
}