快速排序

问题:找临界点挺难的,是了好几次,终于OK了。

 

代码:

#include <iostream>



using namespace std;



void qSort(int arr[],int left,int right)

{

	int i,j;

	int pos;

	static int count=1;

	if(left>=right)

		return;

	

	i=left;

	j=right;

	int key=arr[i];

	pos=i;

    while(i<j)

	{

		while(i<j&&arr[j]>=key)

		{

			j--;

		}

	    if(i<j&&arr[j]<key)

		{

			arr[pos]=arr[j];

	        arr[j]=key;	

			pos=j;

			j--;

		}

		while(i<=j&&arr[i]<=key)

		{

			i++;

		}

	    if(i<=j&&arr[i]>key)

		{

	       arr[pos]=arr[i];

           arr[i]=key;

		   pos=i;

		   i++;

		}



	}

	cout<<"第"<<count<<"次快速排序-"<<j<<":";

	for(int k=left;k<=right;k++)

		cout<<arr[k]<<"  ";

	cout<<endl;

	count++;

	qSort(arr,left,j);

	qSort(arr,j+1,right);



	

	

}



int main()

{

	int arr[]={8,7,6,5,4,3,2,1};

	cout<<"快速排序前:"<<endl;

	for(int i=0;i<8;i++)

	{

		cout<<arr[i]<<"  ";

	}

	cout<<endl<<endl;

	qSort(arr,0,7);

	cout<<endl;

	cout<<"快速排序后:"<<endl;

	for(int j=0;j<8;j++)

	{

		cout<<arr[j]<<"  ";

	}

	cout<<endl;

	return 0;

}

 运行结果:

快速排序

你可能感兴趣的:(快速排序)