这是C++实现的。
void BubbleSort(int arr[], int size)是冒泡排序函数。
其中当发现已经排好序时,会提前退出排序。
#include<iostream>
using namespace std;
void BubbleSort(int arr[], int size);//冒泡排序
void printArray( const int Array[], const int arraySize );//输出数组
int main(){
const int size = 6;
int a[size] ={10,14,26,29,41,52};
cout<<"before sort"<<endl;
printArray(a,size);
BubbleSort(a,size);
cout<<"after sort"<<endl;
printArray(a,size);
system("pause");
return 0;
}
//冒泡排序V[n]不参与排序
void BubbleSort (int V[], int n )
{
bool exchange; //设置交换标志置
for ( int i = 0; i < n; i++ ){
exchange=false;
for (int j=n-1; j>i; j--) { //反向检测,检查是否逆序
if (V[j-1] < V[j]) //发生逆序,交换相邻元素,'<'为从大到小,'>'为从小到大
{
int temp=V[j-1];
V[j-1]=V[j];
V[j]=temp;
exchange=true;//交换标志置位
}
}
if (exchange == false)
return; //本趟无逆序,停止处理
}
}
void printArray( const int Array[], const int arraySize )
{
for( int i = 0; i < arraySize; i++ ) {
cout << Array[ i ] << " ";
if ( i % 20 == 19 )
cout << endl;
}
cout << endl;
}
温馨提示:答案为网友推荐,仅供参考