0

我必须使用快速选择来排序和写入数组的前 N ​​个元素并将它们写在文本上。

问题在于输入文件和我尝试从中读取的数据量。

我使用一个常数 N 来定义我想从文件中读取的最大数量,但到目前为止它只从文件中读取和排序多达 194 个元素。不过,我应该可以用 1000 万美元来做到这一点。

这是代码:

#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;        
}

如果我尝试定义 N=195 或更多,则代码不起作用。

4

0 回答 0