简体   繁体   English

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

[英]In C, I am having trouble with the algorithm of sorting elements from a file from largest to smallest

I have to read a file, allocate an array of size k and store the k largest numbers in the array. 我必须读取一个文件,分配一个大小为k的数组并在数组中存储k个最大的数字。 I know how to scan and read the file and sort it but I don't know how to link them together. 我知道如何扫描和读取文件并对其进行排序,但我不知道如何将它们链接在一起。 I will be really glad if someone could help me out with this issue! 如果有人可以帮我解决这个问题,我将非常高兴!

I have tried to strlen, sizeof, counting loops of fscanf but none of them worked. 我试过strlen,sizeof,计算fscanf的循环,但没有一个工作。 The part with ??? 有???的部分 is where I don know what to put. 是我不知道该放什么的地方。 Generally I would put a amount of elements but in this case amount of elements in the file is unknown. 通常我会放一些元素,但在这种情况下,文件中的元素数量是未知的。

#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("%d\n", arr[i]);                   //Printing data
     }

    free(arr);
    fclose(iFile);

    return 0;
}

Here a proposal, as you I use a sorted array, in my case in ascending order because this seems more 'natural' (to use a descending order change almost nothing). 这是一个提议,因为我使用排序数组,在​​我的情况下按升序排列,因为这似乎更“自然”(使用降序几乎没有变化)。

To sort the 'k' first values I use qsort from the stdlib , and the function comp to do the required comparisons. 为了对'k'排序第一个值,我使用stdlib中的 qsort ,并使用函数comp进行所需的比较。

The main is he function insert , because the array is sorted it is possible to first search where to insert the new element with a complexity log2(k) but after it can be necessary to move the already present elements by 1 position to create the place for the new element, so I prefered to do the search and the move at the same time. 主要是他的函数插入 ,因为数组已经排序,可以首先搜索在哪里插入具有复杂度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 0\n");
  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 in\n", 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 in\n");
        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;
}

Compilation and execution : 编译和执行:

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 

Execution under valgrind : valgrind下执行:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM