Find an array of large numbers N

In the most simple bubble sort, for example, each time through the inner loop to find the largest number of the i-th position (i is an array index for the position, not the large number of i), with a large number comparison is the same as before .

#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");
}
Published 228 original articles · won praise 44 · Views 100,000 +

Guess you like

Origin blog.csdn.net/qq_40945965/article/details/89964666