/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include #include #include /* * qsort.c -- Illustrates the usage of dynamic memory allocation and call by reference. * * The qsort details are based on The Practice of Programming (pp: 32-34) by Brian W. Kernighan and Rob Pike */ /* swap: interchange v[i] and v[j] */ void swap( int v[], int i, int j ) { int tmp; tmp = v[i]; v[i] = v[j]; v[j] = tmp; } /* quicksort: sort v[0]..v[n-1] into increasing * order */ void quicksort( int v[], int n ) { int i = 0, last = 0; if ( n <= 1 ) { /* nothing to do */ return; } swap( v, 0, rand() % n ); /* move pivot elem to v[0] */ for ( i = 1; i < n; i++ ) { /* partition */ if ( v[i] < v[0] ) { swap( v, ++last, i ); } } swap( v, 0, last ); /* restore pivot */ quicksort( v, last ); /* sort smaller values */ quicksort( v+last+1, n-last-1 ); /* sort larger values */ } void print_array( const int array[], int elems ) { int i; printf("{ "); for ( i = 0; i < elems; i++ ) { printf( "%d ", array[i] ); } printf("}\n"); } int main( void ) { int cap = 8; // keep track of capacity int size = 0; // number of items in the array int *nums; // pointer to dynamic array of numbers char line[32]; // input buffer int d; // allocate some memory for the pointer first nums = (int *) malloc(cap * sizeof(int)); assert(nums != NULL); // Read in numbers. Increase memory if we run out of space. while ( fgets(line, sizeof(line), stdin) ) { d = atoi(line); nums[size++] = d; if ( size == cap ) { // increase buffer size if full cap *= 2; nums = realloc(nums, cap * sizeof(int)); assert(nums != NULL); } } // print original, sort, and print sorted print_array(nums, size); quicksort(nums, size); print_array(nums, size); return 0; }