![](/img/trans.png)
[英]Sorting structure variables(3 ints) in file from smallest to largest C
[英]In C, I am having trouble with the algorithm of sorting elements from a file from largest to smallest
我必須讀取一個文件,分配一個大小為k的數組並在數組中存儲k個最大的數字。 我知道如何掃描和讀取文件並對其進行排序,但我不知道如何將它們鏈接在一起。 如果有人可以幫我解決這個問題,我將非常高興!
我試過strlen,sizeof,計算fscanf的循環,但沒有一個工作。 有???的部分 是我不知道該放什么的地方。 通常我會放一些元素,但在這種情況下,文件中的元素數量是未知的。
#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;
}
這是一個提議,因為我使用排序數組,在我的情況下按升序排列,因為這似乎更“自然”(使用降序幾乎沒有變化)。
為了對'k'排序第一個值,我使用stdlib中的 qsort ,並使用函數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 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;
}
編譯和執行:
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
在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.