【C++】聯發科初賽四題《求最大最小數》

1.先上個冒泡排序

/*
求最大最小數
有M個(M<=10000)10進制整數,求出這M個數字中的最大值和最小值。每個數字的絕對值不大於1000000。


【輸入說明】
在程序當前路徑下存在文本文件execute.stdin,程序從execute.stdin中讀取輸入數據。
execute.stdin中的數字用空格隔開。
*/
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
	ifstream ifs("execute.stdin");
	int ival;
	vector<int> vecInt;
	while (ifs >> ival)
		vecInt.push_back(ival);

	ifs.close();

	unsigned int tmp, i = 0, j = 0;
	for (i = 1;i < vecInt.size();++i)
		for ( j = i; j > 0; --j)
			if (vecInt[j-1] < vecInt[j])
			{
				tmp = vecInt[j-1];
				vecInt[j-1] = vecInt[j];
				vecInt[j] = tmp;
			}
	
	cout << vecInt[0] << " " << vecInt[vecInt.size()-1];
	return 0;
}

2.在上個高級點的歸併排序【個人覺得歸併排序雖然穩定,可也難想了點】

/*
求最大最小數
有M個(M<=10000)10進制整數,求出這M個數字中的最大值和最小值。每個數字的絕對值不大於1000000。

【輸入說明】
在程序當前路徑下存在文本文件execute.stdin,程序從execute.stdin中讀取輸入數據。
execute.stdin中的數字用空格隔開。
*/
#include <iostream>
#include <fstream>
using namespace std;
#define MAX 10000
void MergeArray(int a[], int first, int mid, int last, int temp[])
{
	int i = first, j = mid + 1, k = 0;
	int m = mid,   n = last;
	while(i <= m && j <= n)
	{
		if(a[i] < a[j])
			temp[k++] = a[i++];
		else
			temp[k++] = a[j++];
	}	

	while(i <= m)
		temp[k++] = a[i++];

	while(j <= n)
		temp[k++] = a[j++];

	for(i = 0; i < k; ++i)
		a[first + i] = temp[i];
}

void mergesort(int a[], int first, int last, int temp[])
{
	if(first < last)
	{
		int mid = (first + last) / 2;
		mergesort(a, first, mid, temp);
		mergesort(a, mid + 1, last, temp);
		MergeArray(a, first, mid, last, temp);
	}
}

bool MergeSort(int a[], int n)
{
	int *p = new int[n];
	if(p == NULL)
		return false;
	mergesort(a, 0, n - 1, p);
	delete[] p;
	cout << a[n-1] << " " << a[0];
	return true;
}

int main()
{
	int n = 0, iVal, a[MAX];
	ifstream ifs("execute.stdin");
	while (ifs >> iVal)
		a[n++] = iVal; 
	MergeSort(a, n);
	ifs,close();
	system("pause");
	return 0;
}



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