排序算法--快速选择

1.简介

查找集合S中第k个最小元。

平均O(NlogN)

最坏O(N2)

2.实现

/*
选择第k个最小元
*/
/* START: fig7_16.txt */
/* Places the kth smallest element in the kth position */
/* Because arrays start at 0, this will be index k-1 */
void Qselect(ElementType A[], int k, int Left, int Right)
{
	int i, j;
	ElementType Pivot;

	if (Left + Cutoff <= Right)
	{
		Pivot = Median3(A, Left, Right);
		i = Left; j = Right - 1;
		for (;;)
		{
			 while (A[++i] < Pivot){}
			 while (A[--j] > Pivot){}
			 if (i < j)
			    Swap(&A[i], &A[j]);
			 else
				break;
		}
		Swap(&A[i], &A[Right - 1]);  /* Restore pivot */

		if (k <= i)
			Qselect(A, k, Left, i - 1);
		else if (k > i + 1)
			Qselect(A, k, i + 1, Right);
	}
	else  /* Do an insertion sort on the sub array */
		InsertionSort(A + Left, Right - Left + 1);
}
/* END */

ElementType QuickSelect(ElementType A[], int k, int N)
{
	Qselect(A, k, 0, N - 1);

	return A[k - 1];
}

  

原文地址:https://www.cnblogs.com/my-cat/p/5981761.html