zoukankan      html  css  js  c++  java
  • 排序算法--快速选择

    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];
    }
    

      

  • 相关阅读:
    CG_Lession
    linux学习网站大全[转]
    C++ books
    Linux 建议学习路径[转]
    talking C++ STL
    Factory
    计算机图像图形学相关好书推荐
    ASP.NET控件缩写大全
    web开发面试题一
    ASP.Net面试题之二
  • 原文地址:https://www.cnblogs.com/my-cat/p/5981761.html
Copyright © 2011-2022 走看看