Selection in expected linear time

下面的是用C#写的一个算法, 功能是从一个数组中选择第 i 小的一个数, 平均时间复杂度是Θ(n).

using  System;

using  System.Collections.Generic;

using  System.Text;

using  System.Diagnostics;

 

class  Program

{

    
static void Main(string[] args)

    
{

        
int[] array = new int[] 93471051 };

        
int ismall = RandomizedSelect(array, 3);

        Debug.Assert(ismall 
== 4);

    }


 

    
/// <summary>

    
/// select the value of the i-th smallest number of the array

    
/// </summary>


    
static int RandomizedSelect(int[] array, int i)

    
{

        
return RandomizedSelect(array, 0, array.Length - 1, i);

    }


 

    
/// <summary>

    
/// select the value of the i-th smallest number between array[startIndex] and array[endIndex]

    
/// </summary>


    
static int RandomizedSelect(int[] array, int startIndex, int endIndex, int i)

    
{

        
if (startIndex == endIndex)

            
return array[startIndex];

        
int q = Partition(array, startIndex, endIndex);

        
int k = q - startIndex + 1;

        
if (k == i)

            
return array[q];

        
else if (k < i)

            
return RandomizedSelect(array, q + 1, endIndex, i - k);

        
else

            
return RandomizedSelect(array, startIndex, q - 1, i);

    }


 

    
/// <summary>

    
/// partition the array(smaller left, bigger right), return the pivot index

    
/// </summary>


    
static int Partition(int[] array, int startIndex, int endIndex)

    
{

        
//just using the middle number, thought it may not be the best way

        
int mid = (endIndex + startIndex) / 2;

        
int v = array[mid];

        Swap(array, mid, endIndex);

        
int i = startIndex - 1;

        
int j = endIndex;

        
while (true)

        
{

            
while (array[++i] < v) { }

            
while (array[--j] > v) { }

            
if (i > j)

                
break;

            Swap(array, i, j);

        }


        Swap(array, i, endIndex);

        
return i;

    }


 

    
/// <summary>

    
/// swap two numbers in the array

    
/// </summary>


    
static void Swap(int[] array, int index1, int index2)

    
{

        
int temp = array[index1];

        array[index1] 
= array[index2];

        array[index2] 
= temp;

    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值