posts - 3,comments - 0,trackbacks - 0
偶然遇到一个有意思的问题,先记下来

 1
#include <stdio.h>
 2
 3#define MAX 10
 4int a[MAX];
 5int rand_seed = 10;
 6
 7//return 0~32767间一个随机数字
 8int rand()
 9{
10    rand_seed = rand_seed * 110351245 + 12345;
11    return (unsigned int)(rand_seed / 65536% 32768;
12}

13
14void bubble_sort(int a[],const int n)
15{
16    int i,j,t;
17    
18    for(i=0; i < n; i++)
19    {
20        for(j = n - 1; j >= i; j--)
21        {
22            if(a[j] < a[j-1])
23            {
24                t = a[j];
25                a[j] = a[j-1];
26                a[j-1= t;
27            }

28        }

29    }

30}

31
32int main()
33{
34    int i,j;
35        
36    // fill array
37    for (i=0; i < MAX; i++)
38    {
39        a[i] = rand();
40        printf("%d ",a[i]);
41    }

42    printf("\n");
43    bubble_sort(a, MAX);
44    
45    for(j = 0; j < MAX); j++)
46    {
47        printf("%d ",a[j]);
48    }

49
50        return 0;
51}
输出结果:

16838 8723 13221 18534 18069 4560 3644 29292 25286 16198

3644 4560 8723 13221 16198 16838 18069 18534 25286 29292


若将bubble_sort如下定义
void bubble_sort(int a[])  //与前者的区别是少传一个参数n
{
    
int i,j,t;
    
int n = sizeof(a) / sizeof(a[0]);  //数组大小在函数内部获取    
for(i=0; i < n; i++)
    
{
        
for(j = n - 1; j >= i; j--)
        
{
            
if(a[j] < a[j-1])
            
{
                t 
= a[j];
                a[j] 
= a[j-1];
                a[j
-1= t;
            }

        }

    }

}
再调用排序
int main()
{
    
int i,j;
        
    
// fill array
    for (i=0; i < MAX; i++)
    
{
        a[i] 
= rand();
        printf(
"%d ",a[i]);
    }

    printf(
"\n");
    bubble_sort(a);
    
    
for(j = 0; j < sizeof(a) / sizeof(a[0]); j++)
    
{
        printf(
"%d ",a[j]);
    }

        
return 0;
}
输出结果没有排序

16838 8723 13221 18534 18069 4560 3644 29292 25286 16198
16838 8723 13221 18534 18069 4560 3644 29292 25286 16198

n的奥妙啊。。
posted on 2012-05-18 20:20 千万次的问 阅读(139) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理