Sorting Two Dimensional Arrays
I've made two C programs.
The first program writes a binary table to 'sales.dat'.
The second program is what I have a problem with.
I want to sort those numbers in two ways by reading the binary file created by the first program:
1. I want to display the top three number in each of the 12 rows.
(I was thinking of using selection sort for that, but I can't quite get it.)
2. I want to add every number in each column and display the top three sums and its product name.
Please help.
Here is the table I'm trying to base this program of:
Code:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Note A 34 56 27 100 74 56 12 5 87 29 63 16
Note B 9 11 14 55 30 4 47 150 136 26 18 12
Note C 46 3 22 8 78 14 52 27 35 80 123 90
Ballpoin
t pen A 58 38 79 120 85 52 39 23 31 10 10 46
Ballpoin
t pen B 8 5 3 8 2 21 7 3 8 13 8 7
Ballpoin
t pen C 26 32 28 26 24 20 19 22 23 28 30 29
Pencil 12 19 54 51 41 36 20 28 3 5 7 32
Marker 22 14 53 21 25 23 22 180 31 6 213 58
Pencil
case 10 14 43 12 13 17 14 12 11 9 54 15
Erase A 21 20 28 17 19 14 13 12 17 18 14 11
Erase B 24 21 13 24 20 16 13 17 24 38 23 28
The program that writes the file:
Code:
#include<stdio.h>
#include<string.h>
int main(){
FILE* fp;
char filename[]="sales.dat";
int a[11] [12] = {
{34, 56, 27, 100, 74, 56, 12, 5, 87, 29, 63, 16},
{9, 11, 14, 55, 30, 4, 47, 150, 136, 26, 18, 12},
{46, 3, 22, 8, 78, 14, 52, 27, 35, 80, 123, 90},
{58, 38, 79, 120, 85, 52, 39, 23, 31, 10, 10, 46},
{8, 5, 3, 8, 2, 21, 7, 3, 8, 13, 8, 7},
{26, 32, 28, 26, 24, 20, 19, 22, 23, 28, 30, 29},
{12, 19, 54, 51, 41, 36, 20, 28, 3, 5, 7, 32},
{22, 14, 53, 21, 25, 23, 22, 180, 31, 6, 213, 58},
{10, 14, 43, 12, 13, 17, 14, 12, 11, 9, 54, 15},
{21, 20, 28, 17, 19, 14, 13, 12, 17, 18, 14, 11},
{24, 21, 13, 24, 20, 16, 13, 17, 24, 38, 23, 28} };
if(!(fp=fopen(filename, "wb"))){
printf("Can't open a file\n");
return -1;
}
if(fwrite(a, sizeof(int), 132, fp)!= 132){
fclose(fp);
printf("Can't write\n");
return -1;
}
printf("Success to write!\n");
fclose(fp);
}
The program I am having trouble with:
Code:
#include<stdio.h>
int main(){
FILE *fp;
char filename[]="sales.dat";
int a[11] [12];
int k[12];
int sum[12];
char str[11] [50] = {"Note A", "Note B", "Note C", "Ballpoint pen A", "Ballpoint pen B", "Ballpoint pen C",
"Pencil", "Marker", "Pencil case", "Erase A", "Erase B"};
int i, j, tmp, min;
if(!(fp=fopen(filename, "rb"))){
printf("Can't open a file\n");
return -1;
}
if(fread(a, sizeof(int), 132, fp)!=132){
fclose(fp);
printf("Can't read\n");
return -1;
}
printf("Success to read!\n");
fclose(fp);
for(i=0;i<11;i++){
for(j=0;j<12;j++){
printf("%5d", a[i] [j]);
}
printf("\n");
}
for(i=0;i<12;i++){
min = i;
for(j=i+1;j<11;j++){
if(a[0] [min]>a[0] [j]){
tmp = a[0] [min];
a[0] [min] = a[0] [i];
a[0] [i] = tmp;
}
}
}
for(i=0;i<12;i++){
for(j=0;j<11;j++){
sum[i]+=a[i] [j];
printf("%5d", a[i] [j]);
}
printf("\n");
}
return 0;
}