简体   繁体   English

O(n)排序算法

[英]O(n) sorting algorithm

Here's a very horrible sorting algorithm that only works on integers ranging from 0 to size. 这是一个非常可怕的排序算法,只适用于从0到大小的整数。 I wouldn't use such an algorithm on a large set of data or one with large numbers in it because it would require so much memory. 我不会在大量数据或大数据中使用这样的算法,因为它需要这么多的内存。 That consider, wouldn't this algorithm technically run in O(n) time? 考虑一下,这个算法技术上不会在O(n)时间内运行吗?

Thanks 谢谢

#include <iostream>
#define size 33

int main(){

    int b[size];

    int a[size] = {1,6,32,9,3,7,4,22,5,2,1,0};

    for (int n=0; n<size; n++) b[n] = 0;

    for (int n=0; n<size; n++){
        if (size <= a[n]) throw std::logic_error("error");
        b[a[n]]++;
    }

    int x = 0;
    for (int n=0; n<size; n++){
        for (int t=0; t<b[n]; t++){
            a[x] = n;
            x++;
        }
    }

    for (int n=0; n<size; n++) printf("%d ",a[n]);
}

You're showing a variation on radix sort . 您正在显示基数排序的变体。 Along with bucket sort , these algorithms are prime examples of sorting not based on comparison, which can offer better complexity than O(n logn) . 除了桶排序 ,这些算法是不基于比较的排序的主要示例,其可以提供比O(n logn)更好的复杂性。

Do note, however, that your implementation is actually O(n + size) . 但请注意,您的实现实际上是O(n + size)

It is O(n) . 它是O(n) More specifically it is O(n+k) where n is the number of elements in input array and k is the range of input in your case size. 更具体地说,它是O(n + k) ,其中n是输入数组中元素的数量, k是大小写中的输入范围。 You are just keeping counts of all elements which occur in the array. 您只是保留数组中出现的所有元素的计数。 And then you just store them in increasing order as many times as they occur in the original array. 然后,您只需按原样阵列中的顺序存储它们的次数。 This algorithm is called count sort. 该算法称为计数排序。

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

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