以最简单的冒泡排序为例,通过每一次内层循环找到第i个位置的大数(是数组下标为i的位置,不是第i大数),与前一个大数进行比较是否相同。
#include <iostream>
using namespace std;
bool NMax(int a[], int len, int n, int &nNum)
{
if (NULL == a)
{
return false;
}
if (n <= 0 || n >= len)
{
cout << "n超出数组范围!" << endl;
return false;
}
int sum = 1;
for (int i = 0; i < len - 1; i++)
{
for (int j = len - 1; j > i; j--)
{
if (a[j] > a[j - 1])
{
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
if (i > 0)
{
if (a[i] != a[i - 1])
{
sum++;
if (sum == n)
{
nNum = a[i];
return true;
}
}
}
}
cout << "没有第" << n << "大数" << endl;
return false;
}
int main()
{
int data[] = {1, 5, 12, 13, 25, 26, 23, 15, 25, 26, 26};
int length = sizeof(data) / sizeof(int);
int nNumber = 0;
int n = 8;
if (NMax(data, length, n, nNumber))
{
cout << "第" << n << "大数:" << nNumber;
}
system("pause");
}