I have to create a program that finds the k largest elements of a file and stores them in a array size k. It is supposed to read each next element in a file and insert it in the sorted array only if it belongs. I cannot figure out what i am doing wrong. I am reading from a file which contains about 100 numbers. The array is supposed to print out 996 980 956 932 929 in the end but it is printing 386 915 886 793 996. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *file;
int i,j, n, temp;
printf("Enter number of max elements to find:\n");
n = atoi(argv[2]);
int maxnumbers[n];
file = fopen(argv[1], "r");
for(i = 0; i < n; i++)
fscanf(file, "%d", &maxnumbers[i]);
for (i=0; i<n-1; i++)
{
for (j = 0; j< n-1-i; j++)
if (maxnumbers[j] < maxnumbers[j+1])
{
temp = maxnumbers[j];
maxnumbers[j] = maxnumbers[j+1];
maxnumbers[j+1] = temp;
}
}
for (i = 0; i<n; i++)
printf("%d\n", maxnumbers[i]);
while (!feof(file))
{
temp = maxnumbers[n-1];
j = n-1;
fscanf(file,"%d",&i);
if (i > temp)
{
while(i >= maxnumbers[j-1])
{
maxnumbers[j] = maxnumbers[j-1];
j = j-1;
}
maxnumbers[j] = i;
}
}
fclose(file);
for (i = 0; i<n; i++)
printf("%d\n", maxnumbers[i]);
return 0;
}