码迷,mamicode.com
首页 > 其他好文 > 详细

Non-comparison based sort

时间:2014-12-28 07:04:22      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

Bucket Sort:

Scenario:

Work when keys are in a small range.

Linked List.

 

Algorithm(Stable):

1. Walk through each item and enqueue each item into its appropriate queue.

2. Concatenate queues in order

 

Complexity:

O(queue+n):

O(q) time to initialize and concatenate buckets together.

O(n) time to put items to buckets.

 

 

Counting Sort:

Scenario:

Array. When items are keys, no associated values.

 

Algorithm: (Stable, Similar to bucket sort)

Count copies of each key.

 

Complexity:

O(queue+n)

 

For objects, counting sort with complete items for key plus associated item.

for(i=0;i<x.length;i++)

{

  counts[x[i].key]++;

}

//Then, do a scan so counts[i] contains # of keys less than i.

total = 0;

for(j=0;j<counts.length;j++)

{

  c=counts[j];

  counts[j] = total;

  total += c;

}

//let y be output array, counts[i] tells us first index of y to put items with key i.

for(i=0;i<x.length;i++)

{

  y[counts[x[i].key]++]=x[i];

}

 

Radix Sort(Base Sort):

sort 1000 items in range 0~99,999,999

 

Algorithm:

Sort on last digit, then recursively on second digit, up to the most significant digit.

Works because bucket&counting sort are stable.

Faster if we sort on 2 digits at a time(choose radix/base q = 100). For computers, more natural to choose power-of-two radix like q=256

 

Complexity:

each pass inspects log2(q) bits of each key.

if all keys represented in b bits, # of passes is ceiling of b/log2(q)

O((n+q)*ceil(b/log2(q))

 

Non-comparison based sort

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/4189538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!