/*This program sorts an array's values into ascending order*/#include <iostream>using namespace std ;#define SIZE 10int 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.youkuaiyun.com:snippets/2291792.git上述为冒泡排序最基本的代码,而下面的是按引用调用方式的冒泡排序git@code.youkuaiyun.com:snippets/2291984.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 10void 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*/
数组排序之冒泡排序详解篇
最新推荐文章于 2021-10-04 16:52:09 发布