Skip to content

Instantly share code, notes, and snippets.

@bxshi
Created April 16, 2012 02:15
Show Gist options
  • Save bxshi/2396016 to your computer and use it in GitHub Desktop.
Save bxshi/2396016 to your computer and use it in GitHub Desktop.
/*
* Reference
* [1] http://programminggeeks.com/c-code-for-quick-sort/
*
* just add some comments, ALL CODES WAS DONE BY reference[1].
* If that's not cool, just tell me and I'll delete this.
*/
#include "stdio.h"
int split ( int*, int, int ) ;
void quicksort ( int *, int, int ) ;
int main( )
{
int arr[10] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i ;
quicksort ( arr, 0, 9 ) ;
printf ( "\nArray after sorting:\n") ;
for ( i = 0 ; i <= 9 ; i++ )
printf ( "%d\t", arr[i] ) ;
return 0;
}
void quicksort ( int a[ ], int lower, int upper )
{
int i ;
if ( upper > lower )
{
i = split ( a, lower, upper ) ;/* Split into two arrays */
quicksort ( a, lower, i - 1 ) ;/* Sort both arrays */
quicksort ( a, i + 1, upper ) ;
}
}
int split ( int a[ ], int lower, int upper )
{
int i, p, q, t ;
p = lower + 1 ;
q = upper ;
i = a[lower] ;
while ( q >= p )
{
while ( a[p] < i ) /* iterator, if left side element is less than i(split symbol), check next right one */
p++ ;
while ( a[q] > i ) /* another iterator, if right side element is larger than i(split symobl), check left one */
q-- ;
if ( q > p ) /* iterator over, at that time, elements before p is less than i (except i), and elements after q is greater than i */
{
t = a[p] ;
a[p] = a[q] ;
a[q] = t ;
} /* switch p and q element, so p element is less than i and q element is greater than i */
}
/* after that while, the array looks like that(x<i,y>i)
* [i x x x x x y y y y y]
* ^ ^
* q p
*/
t = a[lower] ;
a[lower] = a[q] ;
a[q] = t ;
/* after that swap, the array looks like that(x<i,y>i)
* [x x x x x i y y y y y]
* ^ ^
* q p
*/
return q ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment