1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_array( char **, int);
void insertion_sort( char **, int );
void reverse_sort( char **, int );
char ** names;
int main( int argc, char * argv[] )
{
names = (char**) malloc(sizeof(char*) * argc );
if( argc == 1 )
{
printf( "Please include a list of names\n!" );
return 0;
}
for( int i = 1; i < argc; i++)
{
names[ i - 1 ] = argv[ i ];
}
printf( "Before sort:\n" );
print_array( names, argc - 1 );
printf( "In order:\n" );
insertion_sort( names, argc - 1 );
print_array( names, argc - 1 );
printf( "In reverse order:\n" );
reverse_sort( names, argc - 1 );
print_array( names, argc - 1 );
getchar();
return 0;
}
void print_array( char ** array, int size )
{
int i = 0;
for( i = 0; i < size; i++ )
{
printf( "%d %s\n", i + 1, array[ i ] );
}
}
void insertion_sort( char ** array, int size )
{
int i = 0;
int j = 0;
char * name;
for( i = 0; i < size; i++ )
{
name = array[ i ];
j = i - 1;
while( j >= 0 && strcmp(array[ j ], array[ j + 1 ]) > 0 )
{
array[ j + 1 ] = array[ j ];
j = j - 1;
}
array[ j + 1 ] = name;
}
}
void reverse_sort( char ** array, int size )
{
int i = 0;
int j = 0;
char * name;
for( i = 0; i < size; i++ )
{
name = array[ i ];
j = i - 1;
while( j >= 0 && strcmp(array[ j ], array[ j + 1 ]) < 0 )
{
array[ j + 1 ] = array[ j ];
j = j - 1;
}
array[ j + 1 ] = name;
}
}
|