Created
February 7, 2018 07:00
-
-
Save jarehec/62c7dff89359d77c1b3df22d7d2eb8e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
void print_int_array(int ar[], size_t size) { | |
int i; | |
for (i = 0; i < size; i++) | |
(i + 1) < size ? printf("%d, ", ar[i]): printf("%d\n", ar[i]); | |
} | |
void swap(int *x, int *y) { | |
int tmp = *x; | |
*x = *y; | |
*y = tmp; | |
} | |
int partition(int ar[], int left, int right) { | |
int pivot = ar[left]; | |
int i = right, j; | |
for (j = right; j > left; j--) { | |
if (ar[j] > pivot) { | |
swap(&ar[i], &ar[j]); | |
i--; | |
} | |
} | |
swap(&ar[left], &ar[i]); | |
return (i); | |
} | |
void quick_sort(int ar[], int left, int right) { | |
if (left < right) { | |
int p = partition(ar, left, right); | |
quick_sort(ar, left, p - 1); | |
quick_sort(ar, p + 1, right); | |
} | |
} | |
int main(void) { | |
int ar[] = {1, 3, 2, 4, 6, 5, 7}; | |
size_t size = sizeof(ar) / sizeof(ar[0]); | |
puts("Before sort"); | |
print_int_array(ar, size); | |
quick_sort(ar, 0, size - 1); | |
puts("After sort"); | |
print_int_array(ar, size); | |
return (0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment