数组排序之冒泡排序详解篇

 
 
/*This program sorts an array's values into ascending order*/
#include <iostream>
using namespace std ;
#define SIZE 10
int main ( void ) {
int a [ SIZE ] = { 2 , 6 , 4 , 8 , 10 , 12 , 89 , 68 , 45 , 37 };
int pass ;
int i ;
int hold ;
cout << "Data items in original order" << endl ;
for ( int i = 0 ; i < SIZE ; ++ i ){
cout << " " << a [ i ];
} /*end for*/
/*bubble sort*/
/*loop to control number of passes*/
for ( pass = 1 ; pass < SIZE ; ++ pass ){
for ( i = 0 ; i < SIZE - 1 ; ++ i ) {
if ( a [ i ] > a [ i + 1 ]){
hold = a [ i ];
a [ i ] = a [ i + 1 ];
a [ i + 1 ] = hold ;
} /*end if*/
} /*end inner for*/
} /*end outer for*/
cout << endl ;
cout << "Data items in ascending order" << endl ;
for ( int i = 0 ; i < SIZE ; ++ i ){
cout << " " << a [ i ];
} /*end for*/
cout << endl ;
return 0 ;
}
git@code.csdn.net:snippets/2291792.git
上述为冒泡排序最基本的代码,而下面的是按引用调用方式的冒泡排序
   
   
/*This program puts values into an array, sorts the values into ascending order, and prints the resulting array.*/
#include <iostream>
using namespace std ;
#define SIZE 10
void bubbleSort ( int * const array , const int size ); /*prototype*/
int main ( void ){
int a [ SIZE ] = { 2 , 6 , 4 , 8 , 10 , 12 , 89 , 68 , 45 , 37 };
int i ;
cout << "Data items in original order" << endl ;
for ( i = 0 ; i < SIZE ; ++ i ){
cout << " " << a [ i ];
}
bubbleSort ( a , SIZE );
cout << endl ;
cout << "Data items in ascending order" << endl ;
for ( i = 0 ; i < SIZE ; ++ i ){
cout << " " << a [ i ];
}
cout << endl ;
return 0 ; /*indicates successful termination.*/
}
void bubbleSort ( int * const array , const int size ){
void swap ( int * element1Ptr , int * element2Ptr ); /*prototype*/
int pass ; /*pass counter*/
int j ; /*comparation counter*/
/*loop to control passes*/
for ( pass = 0 ; pass < size - 1 ; ++ pass ){
/*loop to control comparisons during each pass*/
for ( j = 0 ; j < size - 1 ; ++ j ){
/*swap adjacent elements if they are out of order*/
if ( array [ j ] > array [ j + 1 ]){
swap ( & array [ j ], & array [ j + 1 ]);
} /*end if*/
} /*end inner if*/
} /*end outer if*/
} /*end function bubbleSort*/
/*swap values at memory locations to which element1Ptr and element2Ptr point*/
void swap ( int * element1Ptr , int * element2Ptr ){
int hold = * element1Ptr ;
* element1Ptr = * element2Ptr ;
* element2Ptr = hold ;
} /*end function swap*/
git@code.csdn.net:snippets/2291984.git
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值