码迷,mamicode.com
首页 > 编程语言 > 详细

基数排序(radix sort)

时间:2016-09-08 00:46:54      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 #include<iostream>
 2 #include<ctime>
 3 #include <stdio.h>
 4 #include<cstring>
 5 #include<cstdlib>
 6 #include <map>
 7 #include <string>
 8 using namespace std;
 9 // A utility function to get maximum value in arr[]
10 int getMax(int arr[], int n)
11 {
12     int mx = arr[0];
13     for (int i = 1; i < n; i++)
14         if (arr[i] > mx)
15             mx = arr[i];
16     return mx;
17 }
18 
19 // A function to do counting sort of arr[] according to
20 // the digit represented by exp.
21 void countSort(int arr[], int n, int exp)
22 {
23     int output[n]; // output array
24     int i, count[10] = {0};
25 
26     // Store count of occurrences in count[]
27     for (i = 0; i < n; i++)
28         count[ (arr[i]/exp)%10 ]++;
29 
30     // Change count[i] so that count[i] now contains actual position of
31     // this digit in output[]
32     for (i = 1; i < 10; i++)
33         count[i] += count[i-1];
34 
35     // Build the output array
36     for (int i = n-1; i >= 0; i--) {
37         output[count[(arr[i]/exp)%10]-1] = arr[i];
38         count[(arr[i]/exp)%10]--;
39     }
40 
41     // Copy the output array to arr[], so that arr[] now
42     // contains sorted numbers according to curent digit
43     for (i = 0; i < n; i++)
44         arr[i] = output[i];
45 }
46 
47 // The main function to that sorts arr[] of size n using Radix Sort
48 void radixsort(int arr[], int n)
49 {
50     // Find the maximum number to know number of digits
51     int m = getMax(arr, n);
52 
53     // Do counting sort for every digit. Note that instead of passing digit
54     // number, exp is passed. exp is 10^i where i is current digit number
55     for (int exp = 1; m/exp > 0; exp *= 10)
56         countSort(arr, n, exp);
57 }
58 
59 // A utility function to print an array
60 void print(int arr[], int n)
61 {
62     for (int i = 0; i < n; i++)
63         cout << arr[i] << " ";
64 }
65 #if TEST
66 int main(){
67     int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
68         int n = sizeof(arr)/sizeof(arr[0]);
69         radixsort(arr, n);
70         print(arr, n);
71 }
72 #endif
View Code

 

基数排序(radix sort)

标签:

原文地址:http://www.cnblogs.com/guxuanqing/p/5851466.html

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