#include "stdafx.h"
#include<iostream>
using namespace std;
#define N 10
//冒泡排序:两两相邻的数相比,如果不满足排序要求(要求升序或者降序),就进行位置交换
//实际每轮是相邻两个数之间比较将最大的数筛选出来了,然后往后面放(大数沉底)
int _tmain(int argc, _TCHAR* argv[])
{
int a[10]={111,9,25,8,525,16,21,26,499,99};
//j=0:两两相比要比较9(N-1-0)次,j=1:两两相比要比较8(N-1-1)次...j:两两相比要比较(N-1-j)次
int i,j,t;
for(j=0;j<N-1;j++)//控制轮数
{
for(i=0;i<N-1-j;i++)//控制每一轮比较的次数
{
if(a[i]>a[i+1])//(升序):如果右边的数比左边的大
{//元素交换
t=a[i];//将左边的数先赋给一个临时变量t,
a[i]=a[i+1];//将右边的数赋给左边的数
a[i+1]=t;//将左边的数赋给右边,实现元素的交换
}
}
}
cout<<"The sorted number is:"<<endl;
for(i=0;i<N;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
c++实现冒泡排序
最新推荐文章于 2025-05-09 09:13:23 发布