【问题标题】:Ascending sort between numbers in array [closed]数组中数字之间的升序排序[关闭]
【发布时间】:2016-03-20 18:55:29
【问题描述】:

我需要在数组中的数字之间进行排序。

输入.txt: 0005 0006 FFFF 0007 0003 FFFF 0004 0002 0001 FFFF 0000

并且输出应该是: 000 0005 0006 0000 0003 0005 0006 0007 0000 0001 0002 0003 0004 0005 0006 0007

FFFF 在输出中为 0000,并在它们之间进行排序,但要使用整个数组的数字。 我的代码以升序对它们进行排序,这不是正确的输出。 0001 0002 0003 0004 0005 0006 0007 FFFF FFFF FFFF

 // sort the integers
for(i = 1; i < count; i++)
{
    temp = array[i];
    j = i - 1;

    while( (temp < array[j])&&(j >= 0))
    {
        array[j + 1] = array[j];
        j = j - 1;
    }
array[j + 1] = temp;
}

for (i=0; i<count; i++)
{
    printf("%04X ", array[i]);
}

【问题讨论】:

  • 我不明白你在问什么。您所需的输出与您提供的输入不匹配。
  • @WeatherVane 输出应该是这样的。目前我收到:0000 0001 0002 0003 0004 0005 0006 0007 FFFF FFFF FFF。我正在考虑将“if 语句”放在“for 循环”或“while”中。两者都必须尝试。
  • 0xFFFF 不一定是-1。如果您想要-1,请使用-1,并且不要不必要地依赖实现细节。
  • @Olaf 以十六进制格式完成。 -1 或任何其他 FFFF,无所谓
  • @RyadKovach 请编辑问题,以便有一致的问题陈述和所需答案。如果数字到处都是,我只能看到。

标签: c arrays sorting hex insertion-sort


【解决方案1】:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>

#define MAX_DATA_SIZE 100

int main(void){
    const uint16_t block_end = 0xFFFF, input_end = 0x0000;
    uint16_t array[MAX_DATA_SIZE] = {0}, input_value;
    int count = 1;//array[0] = 0x0000

    FILE *fp = fopen("input.txt", "r");

    while(fscanf(fp, "%" SCNx16, &input_value)==1){
        if(input_value == block_end){
            for(int i = 0; i < count; ++i){
                printf("%04" PRIx16 "\n", array[i]);
            }
        } else if(input_value == input_end){
            break;
        } else {
            array[count++] = input_value;
            for(int i = count-1; i > 0 && array[i-1] > array[i]; --i){
                uint16_t temp = array[i];
                array[i] = array[i-1];
                array[i-1] = temp;
            }
            if(count == MAX_DATA_SIZE){
                fprintf(stderr, "There is a need to increase the size of the array.\n");
                exit(1);
            }
        }
    }

    fclose(fp);
    return 0;
}

【讨论】:

猜你喜欢
  • 2012-11-14
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 2014-01-08
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多