對有限數組進行計數排序和求一個無序數組的中位數——題集(十八)

對有限數組進行計數排序和求一個無序數組的中位數——題集(十八)

       今天分享一下,實現對有限數組進行計數排序求一個無序數組的中位數的代碼實現和測試用例。

       數組定義爲:int a[] = {12,13,12,13,19,18,15,12,15,16,17},要求對數組a進行排序,要求時間複雜度爲O(N)。

       對數組a進行計數排序的源代碼和運行示例。

       說明:數組a的大小和值的大小都有限而且比較緊湊,而且要求時間複雜度爲O(N),所以可以考慮使用計數排序,記錄數據出現次數,下標值對應數據值。 

                 計數排序能滿足,值大小在整形範圍內,且有較多重複值的一組數據進行排序。

源代碼如下:

#include<iostream>
using namespace std;
#include<vector>

//對數組進行排序
void CountSort(int* aim, int size){//計數排序
	if(size<=1) return;
	vector<int> tmp;
	tmp.resize(size);
	//int arr[]={0};

	for(int i=0; i<size; i++){
		if(aim[i] > (tmp.size()-1))
			tmp.resize(aim[i]+1);
		++tmp[aim[i]];
	}

	int len=tmp.size();

	int j=0;
	for(int i=0; i<len; i++){
		while(tmp[i]>0){
			aim[j]=i;
			--tmp[i];
			j++;
		}
	}
	
}

void TestCS(){///實現計數排序
	cout<<"對數組進行排序"<<endl<<endl;
	int tmp[]={12,13,12,13,19,18,15,12,15,16,17};
	int len=sizeof(tmp)/sizeof(tmp[0]);
	cout<<"打印原數組: ";
	PrintArr( tmp, len);
	cout<<endl;

	cout<<"打印計數排序後的數組: ";
	CountSort(tmp, len);//計數排序
	PrintArr( tmp, len);
	cout<<endl;
}

int main(){
	TestCS();///實現計數排序

	
	system("pause");
	return 0;
}

運行結果:

 


      求一個無序數組的中位數的源代碼和運行示例。

       如:{2,5,4,9,3,6,8,7,1}的中位數爲5,{2,5,4,9,3,6,8,7,1,0}的中位數爲4和5。

       說明:利用STL的算法make_heap和pop_heap以及STL容器vector。

源代碼如下:

#include<iostream>
using namespace std;

#include<algorithm>
#include<vector>
//求一個無序數組的中位數
void MidNum(int* aim, int size){
	if(size<=0) return;
	if(size==1) cout<<aim[0]<<endl;
	int flag=size/2;//下標值
	vector<int> tmp;
	for(int i=0; i<size; i++){
		tmp.push_back(aim[i]);
	}

	make_heap(tmp.begin(), tmp.end());
	
	for(int i=0; i<flag; i++){
		if(i==flag-1 && size%2==0){
			cout<<tmp[0]<<" ";
		}
		pop_heap(tmp.begin(), tmp.end());
		tmp.pop_back();

	}
	cout<<tmp[0]<<" ";

	return;
}

void TestMidNum(){///求一個無序數組的中位數
	cout<<"求一個無序數組的中位數"<<endl<<endl;
	int tmp[]={2,5,4,9,3,6,8,7,1};
	int len=sizeof(tmp)/sizeof(tmp[0]);
	cout<<"打印原數組: ";
	PrintArr( tmp, len);

	cout<<"打印數組的中位數: ";
	MidNum(tmp, len);//求一個無序數組的中位數
		cout<<endl<<endl;

	int tmp1[]={2,5,4,9,3,6,8,7,1,0};
	len=sizeof(tmp1)/sizeof(tmp1[0]);
	cout<<"打印原數組: ";
	PrintArr( tmp1, len);
	
	cout<<"打印數組的中位數: ";
	MidNum(tmp1, len);//求一個無序數組的中位數

		cout<<endl<<endl;
}
int main(){
		TestMidNum();///求一個無序數組的中位數

	system("pause");
	return 0;
}

運行結果:

 

 

       分享如上,如有錯誤,望斧正!願大家學得開心,共同進步!

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