【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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值