冒泡

来源:互联网 发布:如何做一个淘宝客 编辑:程序博客网 时间:2024/05/09 00:39

最近有个想法:工作之余,在linux下,用c/c++把常用的算法重写一遍。当然,对算法的认识,我仅限于皮毛,我不可能超越那些前辈先知,但我仍想,用自己的方式演示一遍,只当自娱自乐吧!秉承一贯的原则,不讲大道理,只演示关键代码demo,开始算法之旅的第一个算法-----冒泡排序。

1、编辑文件BubbleSort.c,内如如下:

1.#include <stdio.h>  
2.void bubbleSort(int * pArr, int cnt)  3.{ 
4.        int i,j,tmp;  5.        for(i=0;i<cnt;i++)  6.        { 
7.                for(j=i+1;j<cnt;j++)  8.                { 
9.                        if(*(pArr+i)>*(pArr+j))  10.                        { 
11.                                tmp=*(pArr+i); 
12.                                *(pArr+i)=*(pArr+j); 
13.                                *(pArr+j)=tmp; 
14.                        } 
15.                } 
16.        } 
17.} 
18. 
19. 
20.int main(void)  21.{ 
22.        int cnt;  23.        printf("input array length:\n");  24.        scanf("%d",&cnt);  25.        if(cnt<1)  26.        { 
27.                printf("array length must be larger 0 \n");  28.                return 1;  29.        } 
30.        else  31.        { 
32.                printf("array length is %d \n",cnt);  33.        } 
34.        int a[cnt];  35.        int i;  36.        for(i=0;i<cnt;i++)  37.        { 
38.                printf("input arr[%d] value\n",i);  39.                scanf("%d", &a[i]);  40.        } 
41.        bubbleSort(a,cnt); 
42.        printf("bubblesort result:\n");  43.        for(i=0;i<cnt;i++)  44.        { 
45.                printf("%d ",a[i]);  46.        } 
47.        printf("\n");  48.        return 0;  49.} 
2、编译程序

1.[root@localhost gcc]# gcc -o BubbleSort BubbleSort.c  

3、执行

1.[root@localhost gcc]# ./BubbleSort  
2.input array length: 
3.3 
4.array length is 3  
5.input arr[0] value 
6.2 
7.input arr[1] value 
8.1 
9.input arr[2] value 
10.4 
11.bubblesort result: 
12.1 2 4  

本篇文章来源于 Linux公社网站(www.linuxidc.com)  原文链接:http://www.linuxidc.com/Linux/2012-03/55662.htm

原创粉丝点击