算法描述:
-
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
-
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
-
针对所有的元素重复以上的步骤,除了最后一个。
//传统起泡排序
#include<iostream>
#include<stdio.h>
#include<vector>
using namespace std;
vector<int> vt;
void bubbleSort(int lo,int hi);
int
main(void)
{
int n;
scanf("%d",&n);
int tmp;
for(int i=0; i<n; ++i)
{
scanf("%d",&tmp);
vt.push_back(tmp);
}
bubbleSort(0,n-1);
for(int i=0;i<n;i++)
{
printf("%d ",vt[i]);
}
return 0;
}
void bubbleSort(int lo,int hi)
{
for(int i=lo; i<hi; i++)
{
if(vt[i] > vt[i+1])
{
swap(vt[i],vt[i+1]);
}
bubbleSort(lo,hi-1);
}
}