首页 > 编程语言 > 详细

C++实现珠排序

时间:2019-11-20 09:07:43      阅读:209      评论:0      收藏:0      [点我收藏+]
 1 #include <stdio.h>
 2 #include <string.h>
 3 using namespace std; 
 4   
 5 #define BEAD(i, j) beads[i * max + j] 
 6   
 7 // function to perform the above algorithm 
 8 void beadSort(int *a, int len) 
 9 { 
10     // Find the maximum element 
11     int max = a[0]; 
12     for (int i = 1; i < len; i++) 
13         if (a[i] > max) 
14            max = a[i]; 
15   
16     //分配内存
17     unsigned char beads[max*len]; 
18     memset(beads, 0, sizeof(beads)); 
19   
20     // 摆珠子 
21     for (int i = 0; i < len; i++) 
22         for (int j = 0; j < a[i]; j++) 
23             BEAD(i, j) = 1; 
24   
25     for (int j = 0; j < max; j++) 
26     { 
27         // count how many beads are on each post 
28         int sum = 0; 
29         for (int i=0; i < len; i++) 
30         {  
31             sum += BEAD(i, j); 
32             BEAD(i, j) = 0; 
33         }//统计每列高度 
34       
35         // 珠子自由下落 
36         for (int i = len - sum; i < len; i++) 
37             BEAD(i, j) = 1; //i层j列摆珠子
38     } 
39   
40     // Put sorted values in array using beads 
41     for (int i = 0; i < len; i++) 
42     { 
43         int j; 
44         for (j = 0; j < max && BEAD(i, j); j++); 
45   
46         a[i] = j; 
47     } 
48 } 
49   
50 // driver function to test the algorithm 
51 int main() 
52 { 
53     int a[] = {5, 3, 1, 7, 4, 1, 1, 20}; 
54     int len = sizeof(a)/sizeof(a[0]); 
55   
56     beadSort(a, len); 
57   
58     for (int i = 0; i < len; i++) 
59         printf("%d ", a[i]); 
60   
61     return 0; 
62 }

技术分享图片

 

memset

1 #include <iostream>
2 #include <cstring>
3  
4 int main()
5 {
6     int a[20];
7     std::memset(a, 0, sizeof a);
8     for (int ai : a) std::cout << ai << " ";
9 }//20 * 0
 1 /* memset example */
 2 #include <stdio.h>
 3 #include <string.h>
 4 
 5 int main ()
 6 {
 7   char str[] = "almost every programmer should know memset!";
 8   memset (str,-,6);
 9   puts (str);
10   return 0;
11 }
12 //output
13 //------ every programmer should know memset!

珠排序理论参考

https://www.cnblogs.com/kkun/archive/2011/11/23/2260301.html

C++实现珠排序

原文:https://www.cnblogs.com/chenguifeng/p/11894815.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!