#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void selectionSort( int [], int );
int main()
{
const int SIZE = 10;
const int MAXRANGE = 1000;
int sortThisArray[ SIZE ] = {};
srand( time( 0 ) );
// 使用不大于1000的随机数填充数组
for ( int i = 0; i < SIZE; i++ )
sortThisArray[ i ] = 1 + rand() % MAXRANGE;
cout << "\nUnsorted array is:\n";
// 排序前
for ( int j = 0; j < SIZE; j++ )
cout << ' ' << sortThisArray[ j ] << ' ';
selectionSort( sortThisArray, SIZE );
cout << "\n\nSorted array is:\n";
// 排序后
for ( int k = 0; k < SIZE; k++ )
cout << ' ' << sortThisArray[ k ] << ' ';
cout << '\n' << endl;
system("pause");
return 0;
}
void selectionSort( int array[], int size )
{
int temp;
// 排序
if ( size >= 1 )
{
// 选择最小的数放在“开始”位置
for ( int loop = 0; loop < size; loop++ )
{
if ( array[ loop ] < array[ 0 ] )
{
temp = array[ loop ];
array[ loop ] = array[ 0 ];
array[ 0 ] = temp;
}
}
selectionSort( &array[ 1 ], size - 1 );
}
}
选择排序--递归实现
最新推荐文章于 2023-08-28 21:46:36 发布