【问题标题】:given the min and max element in the array, how to sort it?给定数组中的最小和最大元素,如何对其进行排序?
【发布时间】:2018-08-31 01:13:26
【问题描述】:

给定一个包含 n 个整数的数组 A,找到一个算法可以在 O(n + y − x) 时间内对数组 A 进行排序,其中 x 是 A 中的最小整数,y 是 A 中的最大整数。 到目前为止,我只能想到将最小的元素放在 A[0] 中,将最大的元素放在 A[n] 中,有人可以帮忙吗?(作业问题)

#include <stdio.h>
int sort(int array, int x, int y){
    int j = 0;
    int temp = 0;
    for (j<=4){
        if (array[j] == x){
            temp = array[0];
            array[0] = array[j];
            array[j]=temp;
        }
        else if (array[j] == y){
            temp = array[4];
            array[0] = array[j];
            array[j]=temp;
        }
        //////////////////////////////////////////////
        ////////////////////////////////////////////
        ////////////////////////////////////////////
    }
    return 0;
}

int main(){
    int array[5]={3,2,5,4,1};
    sort(array,1,5);
    int i = 0;
    for (i<=4){
        printf("%d\n",array[i]);
    }
    return 0;
}

【问题讨论】:

  • 你有什么问题?
  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。由于您尚未指定编程问题,因此我们无事可做。
  • "Can Someone Help Me?" is not a valid SO question。这通常表明您需要的是与当地导师一起半小时或完成教程,而不是 Stack Overflow。

标签: arrays algorithm


【解决方案1】:

这是间接要求您使用计数排序。这个概念很简单:

  1. 创建一个大小为 y - x 且包含所有 0 个元素的数组
  2. 遍历初始数组,将新数组中与值 [O(n)] 对应的索引加 1
  3. 遍历新数组,输出索引的次数与存储的值一样多 [O(y - x)]

例子:

  • 初始数组[3, 2, 3, 4, 1]

  • 新数组[0, 0, 0, 0]

  • 对应值加1[1, 1, 2, 1]

  • 根据需要多次返回索引[1, 2, 3, 3, 4]

在我们的例子中对应的索引是指value - x

维基百科上也有更深入的解释:https://en.wikipedia.org/wiki/Counting_sort

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 2017-08-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多