{10 14 26 29 41 52}冒泡排序 从大到小

如题所述

这是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;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-16
#include<stdio.h>
#include<math.h>
void main()
{
int i,j,a[6]={10,14,26,29,41,52},temp;
for(i=0;i<5;i++)
for(j=0;j<5-i;j++)
if (a[j]>a[j+1]){temp=a[i];a[i]=a[j];a[j]=temp;}
for(i=0;i<6;i++)printf("%d ",a[i]);
system("PAUSE");
}本回答被提问者和网友采纳
第2个回答  2010-12-17
public static void sort(int[] a){

for(int i=0;i<a.length;i++){

for(int j=0;j<a.length-1;j++){

if(a[j]<a[j+1]){

int k=a[j];
a[j]=a[j+1];
a[j+1]=k;
再用循环把数组输出来 ;

}
}
}
第3个回答  2010-12-18
这到底比较了几次?
相似回答