1. 程式人生 > >C++ 單鏈錶快速排序

C++ 單鏈錶快速排序

#include <string>
#include <stdio.h>
using namespace std;

typedef struct Node
{
	int data;
	Node * next;
}Node;

void swap(Node * A, Node *B)
{	
	cout<<"swap before :"<<A->data<<"  "<<B->data<<endl;
	int temp= A->data;
	A->data=B->data;
	B->data=temp;
	cout<<"swap after :"<<A->data<<"  "<<B->data<<endl;
}


Node* getSeperator(Node * begin, Node * end)
{
	Node * p = begin;
	Node * q = begin->next;
	int key = p->data;
	while(q!=end)
	{
		if(q->data <key)
		{
			p=p->next;
			swap(p,q);
		}
		q=q->next;
	}
	swap(begin,p);
	return p;
}

void quicksort(Node * begin , Node * end)
{
	cout<<"sort begin";
	if(begin!=end)
	{
		Node* sep= getSeperator(begin,end);
		quicksort(begin,sep);
		quicksort(sep->next,end);
	}
}




Node * buildlist()
{
	Node * node;
	string temp;
	int in;
	cin>>in;
	// 這裡假設輸入1000,構建連結串列結束!
	if (in==1000)
	{
		node=NULL;
	}else
	{
		node=new Node();
		node->data=in;
		node->next=buildlist();
	}
	return node;
}

int main()
{
	Node * node= buildlist();
	
	cout<<"before sort ";
	Node * temp=node;
	while (temp!=NULL)
	{
		cout<<temp->data<<endl;
		temp=temp->next;
	}
	quicksort(node,NULL);

	cout<<"after sort ";
	temp=node;
	while (temp!=NULL)
	{
		cout<<temp->data<<endl;
		temp=temp->next;
	}
	system("pause");
}