Created
February 7, 2018 06:59
-
-
Save jarehec/6eb4c05f6b774f32c9f72be6b8b96353 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[right]; | |
int lo = left, hi = right; | |
while (1) { | |
for(; ar[lo] < pivot; lo++) | |
; | |
for(; ar[hi] > pivot; hi--) | |
; | |
if (lo >= hi) | |
return hi; | |
swap(&ar[lo], &ar[hi]); | |
} | |
} | |
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, 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