I have to use quick select to sort and write the first N elements of an array and write them on a text.
The problem is with the input file and the quantity of data I try to read from it.
I use a constant, N, to define the max quantity of number I want to read from the file, but so far it only reads and sorts up to 194 elements from the file. I should be able to do it with 10 million, however.
Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>
#define N 194
float qselect(float *array,int ini, int fin, int k){
int i;
int st = ini;
float tmp;
//finding a pivot
for (i = 0; i < fin - 1; i++) {
if (array[i] < array[fin-1]) {
tmp = array[st];
array[st] = array[i];
array[i] = tmp;
st++;
}
}
//exchanging the pivot with the last element of the array
tmp = array[fin-1];
array[fin-1] = array[st];
array[st] = tmp;
//veryfing the pivot
if (k == st)
return array[st];
else if (st>k)
return qselect(array,ini,st,k);//search on the left
else
return qselect(array,ini+st,fin,k);//search on the right
}
int main(void)
{
FILE *input;
FILE *output;
int range;
//opening the files
input = fopen("numeros.txt","r");
output = fopen("out.txt","w");
printf("Select your N : ");
scanf("%d",&range);
float *array_x;
array_x = malloc(sizeof(float)*N);
float num;
int size=0;
for(int f=0;f<N; f++){
fscanf(input,"%f",&array_x[size]);
size++;
}
int i;
for (i = 0; i < range; i++) {
fprintf(output,"%f ", qselect(array_x,0, size, i));
}
fclose(input);
fclose(output);
free(array_x);
return 0;
}
If I try to define N=195 or more, the code doesn't work.