Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

algorithm - How to sort a list with given range in O(n)

If I have a list of size n and I know that the numbers in the list will be between 1 and 2n how would I go about solving it where the worst case would be O(n)?

I was thinking that if it was between 1 and n I could just take the number and swap it with the value of the array at that number - 1 but then it wouldn't sort if there were any duplicate.

I was thinking of a similar approach for the list having number between 1 and 2n but I can't seem to figure it out. Any help please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Counting Sort can operate in O(n) in your case. Have a look on wikipedia's definition

counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items

http://en.wikipedia.org/wiki/Counting_sort


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...