算法分析之众数问题O(nlogn)

#include
#include

using namespace std;

int mode(vector& a, int left, int right, int& num)
{
	int L = left, R = right;
	int T = a[L];
	while (L < R) {
		while (a[R] >= T && L < R) --R;
		a[L] = a[R];
		while (a[L] < T && L < R) ++L;
		a[R] = a[L];
	}

	int M1 = L;
	R = right;
	while (L < R) {
		while (a[R] > T && L < R) --R;
		a[L] = a[R];
		while (a[L] <= T && L < R) ++L;
		a[R] = a[L];
	}
	a[L] = T;

	int M2 = L;
	int cntm = M2 - M1 + 1;
	num = T;

	int cnt1, cnt2, T1, T2;
	if (left < M1 - 1 && M1 - left + 1 > cntm) {
		cnt1 = mode(a, left, M1 - 1, T1);
		if (cntm < cnt1) {
			cntm = cnt1;
			num = T1;
		}
	}
	if (M2 + 1 < right && right - M2 + 1 > cntm) {
		cnt2 = mode(a, M2 + 1, right, T2);
		if (cntm < cnt2) {
			cntm = cnt2;
			num = T2;
		}
	}

	return cntm;
}

int main()
{
	int n;
	while (cin >> n) {
		if (n <= 0)
			return 0;

		vector a;
		for (int i = 0; i < n; ++i) {
			int j;
			cin >> j;
			a.push_back(j);
		}

		int cnt, num;
		cnt = mode(a, 0, n - 1, num);

		cout << num << endl;
		cout << cnt << endl;
		//cout << num << " : " << cnt << endl;
		for (int i = 0; i < n; ++i)
			cout << a[i] << " ";
		cout << endl;
	}
	return 0;
}


 
 

你可能感兴趣的:(算法分析,搜索,排序)