多路归并排序

题目要求:对整型链表数组(vector<list<int>> src)进行多路归并排序,得到一个有序链表(list<int> dest)。

代码实现:

#include<stdafx.h>
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>


using namespace std;


list <int> merge(vector < list<int> > &src)
{
	size_t list_num = src.size();
	size_t total_elem = 0;
    //对每个链表排序
	for (size_t i = 0; i != list_num; i++) {
		src[i].sort();
		total_elem += src[i].size();
	}
    //堆的实现比较复杂,这里用最简单的方式,当链表的个数很大的时候,需要采用堆。
	list <int> dest;
	while (total_elem--) {
		int min= 0x7fffffff;
		int which= -1;
		for (int i = 0; i != list_num; i++) 
		{
			if (src[i].empty())
				continue;
			if (src[i].front() < min) {
				min = src[i].front();
				which = i;
			}
		}
		if (min!= 0x7fffffff && which != -1) {
			src[which].pop_front();
			dest.push_back(min);
		}
	}
	return dest;
}
int main()
{
	int n;
	vector < list<int> > src;
	cout<<"输入链表个数"<<endl;
	cin >> n; //链表个数
	for (int i = 0; i != n; i++) {
		int m;//第I个链表长度
		cout<<"输出第"<<i<<"个链表元素的个数"<<endl;
		cin >> m;
		list <int> tmp;
		//这里可以输入无序组数
		for (int j = 0; j != m; j++) {
			cout<<"输出第"<<i<<"个链表第"<<j<<"个元素个数"<<endl;
			int x;
			cin >> x;
			tmp.push_back(x);
		}
		src.push_back(tmp);
	}
	//输出所有链表
	for (int i = 0; i != n; i++) {
		for (list <int>::iterator it = src[i].begin(); it != src[i].end(); it++)
			cout << *it << " ";
		cout << endl;
	}
	//
	list <int> dest =merge(src);
	for (list <int>::iterator it = dest.begin(); it != dest.end(); it++)
		cout << *it << " ";
	cout << endl;
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值