快速排序

体会一下不同计数方式的异同,第一种是从0-n-1

第二种是0-n n为无效位

#include <iostream>
#include <ctime>
#include <time.h>
using namespace std;
/************************************************************************/
/* Quick Sort  */
/* author vincent_ynh*/
/*2014-10-19*/
/************************************************************************/

void QuickSort(int *A,int left,int right)
{
	if(left<right)
	{
		int tmp=A[right];
		int i=left,j=right;
		while(i<j)
		{
			while(i<j&&A[i]<tmp)
				i++;
			while(i<j&&A[j]>=tmp)
				j--;
			int a=A[i];
			A[i]=A[j];
			A[j]=a;
		}
		int a=A[i];
		A[i]=tmp;
		A[right]=a;
		QuickSort(A,left,i-1);
		QuickSort(A,i+1,right);
	}
	
}
int main()
{
	int num;
	time_t t_start,t_end;  
	while(cin>>num)
	{
		t_start=time(NULL);
		int *A=new int[num];
		srand(unsigned(time(0)));
		for(int i=0;i<num;i++)
		{
			A[i]=rand()%num;
			cout<<A[i]<<" ";
		}
		cout<<endl;
		QuickSort(A,0,num-1);
		t_end=time(NULL);
		for(int i=0;i<num;i++)
		{
			cout<<A[i]<<" ";
		}
		cout<<endl;
		cout<<"time for "<<num<<":"<<difftime(t_end,t_start)<<endl;
		delete []A;
	}
	
	return 0;
}
#include <iostream>
#include <ctime>
#include <time.h>
using namespace std;
/************************************************************************/
/* Quick Sort  */
/* author vincent_ynh*/
/*2014-10-19*/
/************************************************************************/

void QuickSort(int *A,int left,int right)
{
	if(left<right)
	{
		int tmp=A[right-1];
		int i=left,j=right-1;
		while(i<j)
		{
			while(i<j&&A[i]<tmp)
				i++;
			while(i<j&&A[j]>=tmp)
				j--;
			int a=A[i];
			A[i]=A[j];
			A[j]=a;
		}
		int a=A[i];
		A[i]=tmp;
		A[right-1]=a;
		QuickSort(A,left,i);
		QuickSort(A,i+1,right);
	}
	
}
int main()
{
	int num;
	time_t t_start,t_end;  
	while(cin>>num)
	{
		t_start=time(NULL);
		int *A=new int[num];
		srand(unsigned(time(0)));
		for(int i=0;i<num;i++)
		{
			A[i]=rand()%num;
			cout<<A[i]<<" ";
		}
		cout<<endl;
		QuickSort(A,0,num);
		t_end=time(NULL);
		for(int i=0;i<num;i++)
		{
			cout<<A[i]<<" ";
		}
		cout<<endl;
		cout<<"time for "<<num<<":"<<difftime(t_end,t_start)<<endl;
		delete []A;
	}
	
	return 0;
}



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