When sorting an index table without modifying the data table, you need to make sure that the changes to the index table are reflected in the comparisons for the sort. Here is an algorithm that does this, and also uses a mandatory optimization for bubble sort:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test {
char *str;
int val;
};
void print_sorted ( struct test a[], int n );
int main ( void )
{
struct test a[] = {
{"this", 123},
{"is", 456},
{"a", 789},
{"test", 000}
};
print_sorted ( a, 4 );
return 0;
}
void print_sorted ( struct test a[], int n )
{
int i, j, save;
int *index = malloc ( n * sizeof *index );
if ( index == NULL )
return;
for ( i = 0; i < n; i++ )
index[i] = i;
for ( i = n - 1; i > 0; i-- ) {
int swapped = 0;
for ( j = 0; j < i; j++ ) {
if ( strcmp ( a[index[j]].str, a[index[j + 1]].str ) > 0 ) {
save = index[j];
index[j] = index[j + 1];
index[j + 1] = save;
swapped = 1;
}
}
if ( !swapped )
break;
}
for ( i = 0; i < n; i++ )
printf ( "%s : %d\n", a[index[i]].str, a[index[i]].val );
free ( index );
}
Notice how I used index in the comparison too. That way you don't end up comparing things that you've already compared and botching up the order.