在 C 中,我在从文件中从最大到最小对元素进行排序的算法方面遇到了问题



我必须读取一个文件,分配一个大小为 k 的数组,并将 k 个最大的数字存储在数组中。我知道如何扫描和读取文件并对其进行排序,但我不知道如何将它们链接在一起。如果有人可以帮助我解决这个问题,我将非常高兴!

我试图对 fscanf 进行 strlen、size、count 循环,但没有一个奏效。具有???的部分是我不知道该放什么的地方。通常我会放置一定数量的元素,但在这种情况下,文件中的元素数量是未知的。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
int main(int argc, char *argv[])//
{
    FILE *iFile;
    int k = atoi(argv[1]);//convert strings into int
    int i = 0, j = 0, n = 0, temp = 0;
    int *arr = (int *)malloc(k * sizeof(int));//allocate size k in an array
    iFile = fopen("a.txt", "r");
    if (iFile == NULL)
        return -1;
    while (feof(iFile) <= 0)
    {
        fscanf(iFile, "%d", arr);
        //find number of elements since I have to compare all the numbers with each other

    }
    //reverse
    for (i = 0; i < ??? - 1; i++)                     //Loop for descending ordering
    {
        for (j = 1; j <= ??? - 1; j++)             //Loop for comparing other values
        {
            if (arr[j] < arr[i])                //Comparing other array elements
            {
                temp = arr[i];         //Using temporary variable for storing last temp
                arr[i] = arr[j];            //replacing temp
                arr[j] = temp;             //storing last temp
            }
        }
    }
     for (i = 0; i < k; i++)                     //Loop for printing array 
     data after sorting
     {
printf("%dn", arr[i]);                   //Printing data
     }
    free(arr);
    fclose(iFile);
    return 0;
}

这里有一个建议,就像你一样,我使用排序数组,在我的例子中是升序,因为这似乎更"自然"(使用降序几乎没有变化(。

为了对"k"第一个值进行排序,我使用来自 stdlibqsort,并使用函数 comp 进行所需的比较。

主要是函数插入,因为数组是排序的,所以可以首先搜索在哪里插入具有复杂度 log2(k( 的新元素,但之后可能需要将已经存在的元素移动 1 个位置以创建新元素的位置,所以我更喜欢同时进行搜索和移动。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
/* for qsort */
int comp(const void * p1, const void * p2)
{
  return (*((int *) p1) - *((int *) p2));
}
/* insert v in arr having sz elts */
void insert(int * arr, int v, int sz)
{
  if (v > arr[0]) {
    /* search and move elts to let a hole for the new elt */
    for (int i = 1; i != sz; ++i) {
      if (v <= arr[i]) {
        /* place it in the hole */
        arr[i - 1] = v;
        return;
      }
      arr[i - 1] = arr[i];
    }
    /* v is the greater value */
    arr[sz - 1] = v;
  }
}
int main(int argc, char *argv[])
{
  int k;
  FILE * iFile;
  int * arr;
  if ((argc != 3) || (sscanf(argv[1], "%d", &k) != 1))
    fprintf(stderr, "Usage: %s <number of value> <file>n", *argv);
  else if (k < 1)
    fprintf(stderr, "<number of value> must be greater than 0n");
  else if ((iFile = fopen(argv[2], "r")) == NULL)
    fprintf(stderr, "cannot open '%s'n", argv[2]);
  else if ((arr = malloc(k * sizeof(int))) == NULL)
    fprintf(stderr, "cannot allocate an array of %d inn", k);
  else {
    /* read first 'k' values */
    int i;
    for (i = 0; i != k; ++i) {
      if (fscanf(iFile, "%d", &arr[i]) != 1) {
        fprintf(stderr, "invalid file or too few values inn");
        fclose(iFile);
        return -1;
      }
    }
    /* sort them */
    qsort(arr, k, sizeof(int), comp);
    /* manage all the next values */
    int v;
    while (fscanf(iFile, "%d", &v) == 1)
      insert(arr, v, k);
    fclose(iFile);
    /* print result */
    for (i = 0; i != k; ++i)
      printf("%d ", arr[i]);
    putchar('n');
    free(arr);
    return 0;
  }
  return -1;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall k.c
pi@raspberrypi:/tmp $ cat a.txt 
12 78 6 2 9 56 3 45 21 0 1 56 0
pi@raspberrypi:/tmp $ ./a.out 10 a.txt 
2 3 6 9 12 21 45 56 56 78 
pi@raspberrypi:/tmp $ ./a.out 3 a.txt 
56 56 78 
pi@raspberrypi:/tmp $ ./a.out 1 a.txt 
78 

瓦尔格林德的处决:

pi@raspberrypi:/tmp $ valgrind ./a.out 10 a.txt 
==2217== Memcheck, a memory error detector
==2217== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==2217== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==2217== Command: ./a.out 10 a.txt
==2217== 
2 3 6 9 12 21 45 56 56 78 
==2217== 
==2217== HEAP SUMMARY:
==2217==     in use at exit: 0 bytes in 0 blocks
==2217==   total heap usage: 4 allocs, 4 frees, 5,512 bytes allocated
==2217== 
==2217== All heap blocks were freed -- no leaks are possible
==2217== 
==2217== For counts of detected and suppressed errors, rerun with: -v
==2217== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)

最新更新