关闭

测试list sort,用输出数据,显示过程

324人阅读 评论(0) 收藏 举报
#include<iostream>
#include<list>
using namespace std;

void printlist(list<int> & l)
{
	
	for(list<int>::iterator it=l.begin();it!=l.end();++it)
		cout<<(*it)<<" ";
	cout<<endl;
}


template <typename T>
void sort_list(list<T> &lst)
{
	if(lst.size()<2)
		return;

	list<T> carry;
	list<T> counter[64];
	int fill = 0; 
	typename list<T>::iterator it;

	while (!lst.empty()) 
	{
		carry.splice(carry.begin(), lst, lst.begin());  //一个个的取list的元素 				
		int i = 0;


		cout<<"fill="<<fill<<endl;  //output
		cout<<"carry: ";
		printlist(carry);


		while(i < fill && !counter[i].empty())  //fill加1了,才会运行到这里
		{
			counter[i].merge(carry);
			carry.swap(counter[i]);  //源代码是carry.swap(counter[i++])


			cout<<"while的while的while的carry: ";  //output
			printlist(carry);  
			cout<<"counter[ "<<i<<" ]:";
			printlist(counter[i]);
			i++;
		}
		carry.swap(counter[i]);  
		

	 
		cout<<"after while after while after while的carry: "; //output
		printlist(carry);
		for(int j=0;j<=fill;j++)
		{			
			cout<<"after while after while after while的 counter[ "<<j<<" ]:";
			printlist(counter[j]);
		}
		cout<<endl;

		
		if (i == fill) ++fill;

	} 


    for (int i = 1; i < fill; ++i) 
		counter[i].merge(counter[i-1]);



    lst.swap(counter[fill-1]);

	cout<<"result:";  //output
	printlist(lst);  
}


int main()
{
	int arr[]={10,88,45,87,65,96,84,8,86,53,67,5,48,74,4,35,71,25,32}; //19个元素,fill=5就可以了
	list<int> lst(arr,arr+sizeof(arr)/sizeof(int));

	list<int>::iterator it=lst.begin();
	while(it!=lst.end())
		cout<<*it++<<" ";
	cout<<endl;

	sort_list(lst);  //counter[0]存1个元素,counter[1]存2个元素,...

	return 0;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:22247次
    • 积分:702
    • 等级:
    • 排名:千里之外
    • 原创:48篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条