-
Bubblesort with file
I am stuck on the bublesort portion of my program. Any help for this rookie would be greatly appreciated. Thanks
Code:
void sortFile(FILE *filePtr)
{
int num;
printf("Enter 1 to sort by manufacturer, 2 to sort by M.S.R.P., or 3 to exit: \n");
scanf("%d",&num);
if (num==1)
sortManu(filePtr,vehicle );
else if (num==2)
sortMSRP(filePtr, vehicle );
else
return;
}
void sortManu(FILE *filePtr, record vehicle[])
{
if ((filePtr=fopen("a:\\myfile.dat","r"))==NULL)
printf("\nERROR-can't open file!");
else
{
fread(&vehicle,sizeof(record),1,filePtr);
record car;
int pass,j,hold;
for(pass=1;pass<SIZE-1;pass++)
for(j=0;j<=SIZE-2;j++)
if(car[j].name>car[j+1].name)
{
hold=car[j].name;
car[j].name=car[j+1].name];
car[j+1].name=hold;
}
}
}
void sortMSRP(FILE *filePtr, record vehicle[])
{
if ((filePtr=fopen("a:\\myfile.dat","r"))==NULL)
printf("\nERROR-can't open file!");
else
{
fread(&vehicle,sizeof(record),1,filePtr);
record car;
int pass,j,hold;
for(pass=1;pass<SIZE-1;pass++)
for(j=0;j<=SIZE-2;j++)
if(car[j].msrp>car[j+1].msrp)
{
hold=car[j].msrp;
car[j].msrp=car[j+1].msrp];
car[j+1].msrp=hold;
}
}
}
}
-
First of all, load your whole file into memory and run your bubblesort on it there. then write it back out to disk into another _sorted_ file. Much faster, much simpler, and it preserves your original data file.
Second, flow chart, flow chart, flow chart. there's nothing hard about flowcharting to find your errors. Only mere amateurs avoid this powerful tool.
Thirdly, bubble sort is very simple--
Code:
1) checkValue = a value lower or as low as any you might find in the data set.
2) aValue = first value in data block
3) if EOF, bail
4) if aValue > checkValue:
4a) swap position of both values in data set.
4b) remember what highest value is: checkValue = aValue;
4c) reset aValue to first value in data block
4d) goto step 3
5) increment aValue to _next_ character in data set
6) goto step 3
Hopefully this will help