打乱数组顺序

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 int * neworder(int len);
 5 
 6 int main()
 7 {   
 8     int a[7] = {45, 23, 12, 56, 4, 78, 56};
 9     int i = 0;
10     int *b = neworder(7);
11     
12     for(i = 0; i < 7; i++)
13     {
14         printf("%d ", a[b[i]]);
15 
16     }
17     printf("\n");
18 
19     free(b);//释放内存
20     system("pause");
21     return 0;
22 }
23 
24 int * neworder(int len)//新的下标顺序,好繁琐,待优化
25 {  
26    int temp = 0, count = 0, num = 0;
27    int i = 0;
28    int *b = NULL;
29 
30    srand((unsigned)time(NULL));
31    b = (int*)malloc(sizeof(int) * len);
32  
33    while(count < len)
34    {
35       temp = rand() % len;
36       if(0 == count)
37       {   
38           b[0] = temp;
39           count++;
40       }
41 
42       num = 0;
43       for(i = 0; i < count; i++)
44       {
45           if(b[i] == temp)
46           {                 
47               break;
48           }
49           else
50           {
51              num++;//记录不相等的个数
52           }
53       }
54      
55       if(num == count)
56       {
57           b[count] = temp;
58           count++;
59       }
60    }
61 
62    return b;
63 }
View Code

 

posted @ 2013-08-08 09:53  kongmeng  阅读(218)  评论(0编辑  收藏  举报