Skip to content

Instantly share code, notes, and snippets.

@boki1
Created April 27, 2019 22:03
Show Gist options
  • Save boki1/6e06919e49785347c9a8bd427ec70947 to your computer and use it in GitHub Desktop.
Save boki1/6e06919e49785347c9a8bd427ec70947 to your computer and use it in GitHub Desktop.
Quicksort implementation - School HW - 21/04/2019
#include <stdio.h>
#include <stdlib.h>
#define swap(x, y) ((&(x) == &(y)) ? (x) : ((x)^=(y), (y)^=(x), (x)^=(y)))
#define dim(arr) (sizeof(arr) / sizeof(*arr))
int make_partition(int arr[], int beg, int end)
{
int pivot = arr[end], i = beg - 1;
for (int j = beg; j < end; ++j)
{
if (arr[j] <= pivot)
{
++i;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[end]);
return i + 1;
}
void quicksort(int arr[], int beg, int end)
{
if (beg > end)
return;
int p = make_partition(arr, beg, end);
quicksort(arr, beg, p - 1);
quicksort(arr, beg + 1, end);
}
int main(int argc, const char const *argv[])
{
int arr[] = { 3, 2, 5, 4, 1 };
int len = dim(arr);
quicksort(arr, 0, len - 1);
for (int i = 0; i < len; ++i)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment