快排优化代码__2018.07.26

代码:

======4、快速排序优化==============
int Partion(int *arr,int low,int high)
{
	int tmp = arr[low]; 
	while(low < high)
	{
		while(low < high && arr[high] >= tmp)
		{
			high--;
		}
		if(low >= high)
		{
			break;
		}
		else
		{
			arr[low] = arr[high];
		}

		while(low < high && arr[low] <= tmp)
		{
			low++;
		}
		if(low >= high)
		{
			break;
		}
		else
		{
			arr[high] = arr[low];
		}
	}
	arr[low] = tmp;
	return low;
}
void Swap(int *arr,int start,int end)
{
	int tmp = arr[start];
	arr[start] = arr[end];
	arr[end] = tmp;
}
void Focus_Same_Num(int *arr, int low, int par, int high, int *left, int *right)   //优化4
{
	if(low < high)
	{
		int ParLeftIndex = par-1;
		int ParRightIndex = par+1;
		for(int i = par-1;i >= low;i--)
		{
			if(arr[i] == arr[par] )//如果两个值相等,那么交换,如果不是紧挨着的
			{
				if(i != ParLeftIndex)
				{
					Swap(arr,i,ParLeftIndex);//把相等的拉过来,聚集在一起
					ParLeftIndex--;
				}
				else
				{
					ParLeftIndex--;
				}
				
			}
		}
		*left = ParLeftIndex;

		for(int i = par+1;i <= high;i++)
		{
			if(arr[i] == arr[par])
			{
				if(i != ParRightIndex)
				{
					Swap(arr,i,ParRightIndex);
					ParRightIndex++;
				}
				else
				{
					ParRightIndex++;
				}
			}
		}
		*right = ParRightIndex;
	}
}
void Quick(int *arr, int low, int high)
{
	if (low < high)                             
	{
		int par = Partion(arr, low, high);
		int left = par - 1;
		int right = par + 1;
		//优化方式2:
		Focus_Same_Num(arr, low, par, high, &left, &right);   
		//Qsort(arr, low, left);            //分治左边序列
		//Qsort(arr, right, high);            //分治
		printf("par == %d\n",par);
		printf("left == %d\n",left);
		printf("right == %d\n",right);
		if(par > low+1)
		{
			Quick(arr,low,left);//par-1
		}
		if(par < high-1)
		{
			Quick(arr,right,high);////par+1
		}
	}
}
void QuickSort(int *arr,int len)
{
	Quick(arr,0,len-1);
}

 

你可能感兴趣的:(代码)