排序算法之——冒泡排序(一)

来源:互联网 发布:站内优化 编辑:程序博客网 时间:2024/06/14 21:06

冒泡排序:
假设数组长度为N,从大到小进行排序
1.比较相邻前后两个数据,如果前一个小于后面的数据,就将两数交换
2.这样对数组进行一次遍历,则最小数“浮”到最后
3.N = N -1 ,重复前两步

#include<stdio.h>#include<math.h>#define N 10using namespace std;int main (int argc,char *argv[]){    int temp;    int a[N];    int i;    int j;    for(i = 0; i < N ;i++)    {        a[i] = rand()%100;    }    for(i = 0;i < N ;i++)    {         for(j = 1;j < N - i;j++)         {             if(a[ j- 1] < a[j])             {                 temp = a[j-1];                 a[j-1] = a[j];                 a[j ] = temp;             }         }    }    for(j= 0 ;j< N;j++)    {        printf("  %d",a[j]);        printf("\n");    }    return 0;}

运行结果:

90
69
67
64
62
58
41
34
24
0
Press any key to continue

0 0
原创粉丝点击