SELECT 算法
// main.cpp
// Find the N-th minimum value, based on Partition
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std ;
int Minimum_N(int arr[], int s, int e, int n)
{
// Partition
int j = s ;
for (int i = s ;i < e-1 ;i++)
{
// Exchage two integer
if (arr[i] < arr[e-1])
{
swap(arr[i], arr[j]) ;
j++ ;
}//if
}//for
swap(arr[j], arr[e-1]) ;
ostream_iterator<int> out(cout, " ") ;
copy(arr+s, arr+e, out) ;
cout <<endl ;
// Find Minimum_N
if (n > j+1)
{
return Minimum_N(arr, j+1, e, n) ;
}
else if (n < j+1)
{
return Minimum_N(arr, s, j, n) ;
}//if
return arr[j] ;
}
int main()
{
int arr[] = {3, 2, 6, 1, 9, 7, 0, 8, 4, 5} ;
ostream_iterator<int> out(cout, " ") ;
copy(arr, arr + sizeof(arr)/sizeof(arr[0]), out) ;
cout <<endl ;
cout <<"Minimum 2 : " <<Minimum_N(arr, 0, sizeof(arr)/sizeof(arr[0]), 2) <<endl ;
return 0 ;
}
不完全排序, 查找第 N 小的元素.