0

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.

Laurel
  • 5,965
  • 14
  • 31
  • 57
  • BTW, did you realize that you are calling `qselect` in a loop? Is that the intent? – R Sahu Sep 28 '16 at 15:54
  • What did your debugger tell you about the segmentation fault? If you didn't use a debugger on the above code, you should have done so before asking here. – Random Davis Sep 28 '16 at 16:00
  • The only place you use `range` is the final `for` loop. Everywhere else you're using the defined constant `N` which is 194. You either need to use `N` everywhere, or `range` everywhere. – user3386109 Sep 28 '16 at 16:00
  • 1
    It will certainly go wrong if `range` is greater than `N`. – Ian Abbott Sep 28 '16 at 16:03

0 Answers0