题意:输出一串数字的中间数。
题解:
#include <iostream>
using namespace std;
void quiksort ( int * array, int left, int right )
{
if ( left < right )
{
int s = array [( left + right ) / 2];
int l = left - 1, r = right + 1;
while ( 1 )
{
while ( array[++l] < s );
while ( array[--r] > s );
if ( l >= r )
break;
swap ( array[l], array[r] );
}
quiksort ( array, left, l - 1 );
quiksort ( array, r + 1, right );
}
}
int main()
{
int n, array[10010];
cin >> n;
for ( int i = 0; i < n; i++ )
cin >> array[i];
quiksort(array,0,n-1);
cout << array[n/2] << endl;
return 0;
}
或者
#include <iostream>
using namespace std;
int array[10010];
int part ( int left, int right )
{
int i = left - 1;
int s = array[right];
for ( int j = left; j < right; j++ )
{
if ( array[j] <= s )
{
i++;
swap ( array[i], array[j] );
}
}
swap ( array[right], array[i+1] );
return i + 1;
}
void Qsort ( int left, int right )
{
if ( left >= right )
return;
int p = part ( left, right );
Qsort(left,p-1);
Qsort(p+1,right);
}
int main()
{
int n;
cin >> n;
for ( int i = 0; i < n; i++ )
cin >> array[i];
Qsort(0,n-1);
cout << array[n/2] << endl;
return 0;
}