My task is to create a sorting algorithm for integer values read from a file. The values have to be sorted in an array, as the amount of values is variable, I've used a dynamic array of integers (actually my first time).
Now, the algorithm seems to work fine as it prints all values in the correct order, but only until there are 6 values to sort. In that case, there's no output whatsoever, it seems like even the sorting process isn't successful anymore.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b){
..
}
int main(){
int i,anzahl,sorted=0,bla;
FILE *fp;
int* feld;
fp=fopen("file","r");
if (fp==NULL) return 0;
else {
fscanf(fp,"%i",&anzahl);
feld=(int*)calloc(anzahl,sizeof(int));
for (i = 0; i <= anzahl; ++i) {
fscanf(fp,"%i",&bla);
*(feld+i)=bla;
}
fclose(fp);
while (sorted==0){
for (i = 0; i < anzahl-1; ++i) {
if (feld[i]>feld[i+1]) swap(&feld[i],&feld[i+1]);
}
for (i = 0; i < anzahl-1; ++i) {
if (feld[i]<=feld[i+1]) sorted=1;
else {sorted=0; break;}
}
}
for (i = 0; i <anzahl; ++i) {
printf("%i ",feld[i]);
}
}
return 0;
}
Please excuse the German variable names and the newbie-style code.
If now the content of my "file" is as follows:
6
1
5
1
99
7
8
the program won't work. If I change the number of values, everything is fine, but as long as the number of values is 6, the program won't work, no matter what values there are.
void swap(int *a, int *b) { .. }is the function too complex to post it?blapermanently in your source