Hello,
I'm pretty new to C programming, and am working on an assignment that uses the quicksort algorithm adapted to sort strings. I got it working OK except for the fact that it only seems to be looking at the first character in each string. I'm at a loss trying to figure out where the problem is. Anyone have any clues?
I'm testing it by piping it the contents of a file named "test" that contains the following:
I'm trying to get the output to be:
Instead, I'm getting:
Here's how I'm executing it:
Code:
$ cat test | ./a.out
Anyway, here's the c code. Sorry for the huge post.
Code:
//-----------------------------COMPILER DIRECTIVES------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
//-----------------------------FUNCTION PROTOTYPES------------------------------
void quicksort( char *[], int );
void swap( char *[], int, int );
//----------------------------------CONSTANTS-----------------------------------
const long LINE_CAP = 1000000; // Max number of strings (lines)
const short STR_CAP = 82; // Max characters per string +2 for '/0'
//--------------------------------MAIN FUNCTION---------------------------------
int main() {
// Declare Variables
long lngLinesRead = 0; // Keeps track of how many data lines exist
char *pcLine[LINE_CAP]; // Array of character arrays
char cLine[STR_CAP]; // Buffer for the array of characters
int i; // Iterator for loops
// Read the char array into the buffer while EOF is not reached
while( fgets( cLine, STR_CAP, stdin ) != NULL ) {
// Allocate space at the nth pointer in pcLine array
pcLine[lngLinesRead] = (char *) malloc( sizeof( cLine ) );
// Set the value in the pointer to the value of the character array
*(pcLine[lngLinesRead]) = *cLine;
// Increment to next line
lngLinesRead++;
}
// Sort the lines
quicksort( pcLine, lngLinesRead );
// Print to standard output
for( i = 0; i < lngLinesRead; i++ ) {
printf( "%s\n", pcLine[i] );
free( pcLine[i] );
}
// Return error free
return 0;
}
//-----------------------------FUNCTION DEFINITIONS-----------------------------
// swap: interchange v[i] and v[j].
void swap( char *v[], int i, int j )
{
char *temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
// quicksort: sort v[0]..v[n-1] into increasing order.
void quicksort( char *v [], int n )
{
int i, last;
if( n <= 1 ) // nothing to do
return;
swap( v, 0, rand() % n ); // move pivot element to v[0]
last = 0;
for ( i = 1; i < n; i++ ) // partition
if ( strcmp( v[i], v[0] ) < 0 )
swap( v, ++last, i );
assert(( last >= 0 ) && ( last < n ));
swap( v, 0, last ); //restore pivot
quicksort( v, last ); // recursively sort each part
quicksort( v+last+1, n-last-1 );
}
Thanks for the help, I really appreciate it.