Created
October 28, 2017 08:50
-
-
Save PtxDK/26ffa8dfaf761244d4698dc3ff07d5a7 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
// quickSort.c | |
#include <stdio.h> | |
void quickSort( int[], int, int); | |
int partition( int[], int, int); | |
void main() | |
{ | |
int a[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9}; | |
int i; | |
printf("\nUnsorted array is: "); | |
for(i = 0; i < 9; ++i) | |
printf(" %d ", a[i]); | |
quickSort( a, 0, 8); | |
printf("\n\nSorted array is: "); | |
for(i = 0; i < 9; ++i) | |
printf(" %d ", a[i]); | |
printf("\n\n"); | |
} | |
void quickSort( int a[], int l, int r) | |
{ | |
int j; | |
if( l < r ) | |
{ | |
// divide and conquer | |
j = partition( a, l, r); | |
quickSort( a, l, j-1); | |
quickSort( a, j+1, r); | |
} | |
} | |
int partition(int a[], int l, int r) { | |
int pivot, i, j, t; | |
pivot = a[l]; | |
i = l; j = r+1; | |
while(1) | |
{ | |
do ++i; while( a[i] <= pivot && i <= r ); | |
do --j; while( a[j] > pivot ); | |
if( i >= j ) break; | |
t = a[i]; | |
a[i] = a[j]; | |
a[j] = t; | |
} | |
t = a[l]; | |
a[l] = a[j]; | |
a[j] = t; | |
return j; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment