快速选择

选择第K个最大(小)元

private static super AnyType>>
void quickSelect(AnyType a, int left, int right, int k)
{
   if(left+ CUTOFF <= right)
   {
      AnyType pivot= median3(a, left, right);
      //Begin partitioning
      int i= left, j= right-1;
      for(; ;)
      {
         while(a[++i].compareTo(pivot) < 0) { }
         while(a[--j].compareTo(pivot) > 0) { }

         if( i < j)
            swapReferences(a, i, j);
         else
            break;
      }

      //Restore pivot
      swapReferences(a, i, right-1);

      if( k <= i)
         quickSelect(a, left, i-1, k);
      else if( k> i+ 1)
         quickSelect(a, i+1, right, k);
   }

   else  //Do an insertion sort on the subarray
      insertionSort(a, left, right);
}

你可能感兴趣的:(快速选择,算法,数据结构与算法分析)