冒泡排序原理及代码实现

来源:互联网 发布:防火知多少ppt图片 编辑:程序博客网 时间:2024/05/29 15:50
//比较相邻的元素,如果第一个比第二个大,就交换他们两个的位置
//对每一对相邻的元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素是最大的
//针对所有的元素重复以上的步骤,除了最后一个。
//持续每次对越来越少的元素重复以上的步骤,直到没有任何一对数字需要比较位置
//冒泡排序的最好情况的复杂度是O(n);最差的复杂度是O(n^2),平均复杂度是O(n^2)
//冒泡排序最好的情况下的执行的比较次数是n-1,最坏的情况下是n*(n-1)/2


#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;


void BubbleSort(int a[],int n);


int _tmain(int argc, _TCHAR* argv[])
{

int num[]={23,19,16,78,94,24,28};
int SIZE=sizeof(num)/sizeof(int);
BubbleSort(num,SIZE);
for(int k=0;k<SIZE;k++)
printf("%d ",num[k]);

system("pause");
return 0;
}


void BubbleSort(int a[],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
0 0