從n個數中找出前m個最大的

我的思路:首先從文件中讀取m個,存入數組Top[n],並維護一個最大值Max和一個最小值Min,然後:

while (讀一個數據)

         if (該數比Max大)

                並把該數插入Top[n]中//使用插入排序,把多餘的那個移除

更新Max

else if (該數比Min小)

//無需處理

else

並把該數插入Top[n]中


代碼實現如下[C++]:

#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
class Top
{
public:
	Top (int m = 10, int n = 2): pre_d (n)
	{
		ofs.open ("source.dat");
		ifs.open ("source.dat");
		top = new int[n];
		create (m);
		max = 0;
		min = 0;
	}
	void create (int n)
	{
		for (int i = 0; i < n; i++)
		{
			ofs<< rand () <<endl;
		}
		ofs.close ();
	}
	void topN ()
	{
		int tmp;
		for (int i = 0; i < pre_d; i++)
		{
			ifs>> top[i];
		}
		sort (top, top+pre_d);
		min = top[0];
		max = top[pre_d-1];
		while (ifs>> tmp)
		{
			if (tmp > min)
			{
				updat (top, pre_d, tmp);
			}
		}
		ofstream ofs ("out.dat");
		for (int i = 0; i < pre_d; i++)
		{
			ofs<<top[i]<<endl;
		}
		ofs <<"min: " <<min <<endl;
		ofs <<"max: " <<max <<endl;
	}

	void updat (int *dat, int length, int x)
	{
		int i = length-1;
		while ((dat[i] >= x) && (i > 0))	
			i--;
		if (i < 0)
			return;
		for (int j = 1; j <= i; j++)
		{
			dat[j - 1] = dat[j];
		}
		dat[i] = x;
		min = dat[0];
		max = dat[length - 1];
	}
private:
	ofstream ofs;
	ifstream ifs;
	int *top;
	int max;
	int min;
	int pre_d;	//找出前多少個
};
<pre name="code" class="cpp">int main ()
{
        Top t (10000, 100);
	t.topN ();
	return 0;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章