// structselsort1c: use selection sort to sort 'n' colour+code structs according to 'code'
#include <stdio.h>
#include <stdlib.h>
#define MAXNAME 20
typedef struct {
char colour[MAXNAME];
int code;
} Colourcode;
void selsort(Colourcode array[], int n);
int main(int argc, char **argv) {
Colourcode *array;
int readError = 0;
int number;
if (scanf("%d", &number) == 1) { // read the 'n'
array = (Colourcode *)malloc(number * sizeof(Colourcode)); // get memory to hold 'n' Colourcodes
assert(array != NULL);
int i;
for (i=0; i<number && !readError; i++) {// fill the array
if (scanf("%s %d", array[i].colour, &array[i].code) != 2) {
readError = 1;
}
}
} else {
readError = 1;
}
if (!readError && number>0) {
///////////////////////////
selsort(array, number); // sort the array of structs
/////////////////////////
printf("Sorted codes:");
int i;
for (i=0; i<number; i++) {
printf(" %s:", array[i].colour);
printf("%d", array[i].code);
}
putchar('\n');
}
return EXIT_SUCCESS;
}
void selsort(Colourcode array[], int length) { // selection sort
int i;
int min;
int marker;
for (marker=0; marker<length; marker++) {
min = marker; // assume element 'marker' is minimum
for (i = marker+1; i<length; i++) {
if (array[i].code < array[min].code)
min = i; // found a better min at location 'i'
}
Colourcode tmp;
tmp = array[marker];
array[marker] = array[min]; // swap element 'min' and 'marker'
array[min] = tmp;
}
}
|