Code:
/*
Key Priorities:
key0 = price,
key1 = year
key2 = month
key3 = postcode
key4 = bedrooms
postcode, month, year, bedroom, price
*/
#include <stdio.h>
#define N 5
#define R 21
void sort(unsigned long data[R][N]);
void swap_rows(unsigned long data[][N], int i, int j); //swaps data[i] and data[j]
int main() {
FILE *fp;
char buff[80] = {'\0'};
int i, j, n ;
unsigned long int data[R][N] = {{ 0 }};
if((fp = fopen("multiKey.txt", "rt")) == NULL) {
printf("\nError opening file");
return 1;
}
//get past 2 header rows
fgets(buff, sizeof(buff), fp);
fgets(buff, sizeof(buff), fp);
printf("\n\n\n");
j = 0;
for(i = 0; i < R; i++) {
fscanf(fp, "%U%U%U%U%U",
&data[i][j],&data[i][j+1],&data[i][j+2],&data[i][j+3],&data[i][j+4]);
printf("%lu %lu %lu %lu %lu\n",
data[i][j],data[i][j+1],data[i][j+2],data[i][j+3],data[i][j+4]);
}
sort(data);
printf("\n\n\t\t\t press enter when ready");
fclose(fp);
i = getchar(); ++i;
return 0;
}
/* Key Priorities: key0 = price, key1 = year key2 = month key3 = postcode
key4 = bedrooms
Order in file: postcode, month, year, bedroom, price
*/
void sort(unsigned long data[R][N]) {
int i, j, pc, mo, yr, bed, price;
pc = 0; mo = 1, yr = 2, bed = 3, price = 4;
for(i = 0; i < R; i++) { //sort by price
for(j = i +1; j < R; j++)
if(data[i][price] > data[j][price])
swap_rows(data, i, j);
else if((data[i][price] == data[j][price]) &&
(data[i][yr] > data[j][yr]))
swap_rows(data, i, j);
}
/* this is a naive way to resort according to multiple keys. It does
exactly the same thing as the "else if(" statement, directly above this
*/
/* printf("\n\n");
for(i = 0; i < R; i++) { //sort by year
for(j = i +1; j < R; j++)
if((data[i][price] == data[j][price]) && (data[i][yr] > data[j][yr]))
swap_rows(data, i, j);
}
*/
printf("\n\n");
/* You can keep the naive approach, but why not add it into the main
sorting loops, up above, just like was done with the code right
above this?
*/
for(i = 0; i < R; i++) { //sort by month
for(j = i +1; j < R; j++)
if(data[i][price]==data[j][price]) {
if((data[i][yr] == data[j][yr]) && (data[i][mo] > data[j][mo]))
swap_rows(data, i, j);
}
}
printf("\n\n");
//show in row order, and priority in left to right columns
for(i = 0; i < R; i++) {
printf("%lu %lu %lu %lu %lu\n",
data[i][price],data[i][yr],data[i][mo],data[i][pc],data[i][bed]);
}
}
void swap_rows(unsigned long data[R][N], int i, int j) { //swaps data[i] and data[j]
int k;
unsigned long temp[N];
for(k = 0; k < N; k++) //make assignments to temp
temp[k] = data[i][k];
for(k = 0; k < N; k++) //make assignments to i
data[i][k] = data[j][k];
for(k = 0; k < N; k++) //make assignments to j
data[j][k] = temp[k];
}
I've run this through and not seen any problems, but that's not saying it's been tested, and it IS incomplete.