An array of length N can contain values 1,2,3 … N^2. Is it possible to sort in O(n) time?

放肆的年华 提交于 2020-01-09 10:09:52

问题


Given an array of length N. It can contain values from ranging from 1 to N^2 (N squared) both inclusive, values are integral. Is it possible to sort this array in O(N) time? If possible how?

Edit: This is not a homework.


回答1:


Write each integer in base N, that is each x can be represented as (x1, x2) with x = 1 + x1 + x2*N. Now you can sort it twice with counting sort, once on x1 and once on x2, resulting in the sorted array.




回答2:


Yes, you can, using radix sort with N buckets and two passes. Basically, you treat the numbers as having 2 digits in base N.




回答3:


It is possible to sort any array of integers with a well defined maximum value in O(n) time using a radix sort. This is likely the case for any list of integers you encounter. For example if you were sorting a list of arbitrary precision integers it wouldn't be true. But all the C integral types have well-defined fixed ranges.



来源:https://stackoverflow.com/questions/4238460/an-array-of-length-n-can-contain-values-1-2-3-n2-is-it-possible-to-sort-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!