期望为线性时间的选择算法RANDOM_SELECT

#include<iostream>
#include<ctime>
using namespace std;
int Partition(int *A, int p, int r)// 划分
{
    int x = A[r];
    int i = p - 1;
    for (int j = p; j < r; j++)
    {
        if (A[j] < x)
        {
            i++;
            swap(A[i],A[j]);
        }
    }
    swap(A[i+1],A[r]);
    return (i+1);
}
int Rand(int M, int N)//实现区间为[M,N]的随机数
{
    return (int)((double)rand() / (double)RAND_MAX*(N - M + 1) + M);
}
int Randmom_Partion(int *A, int p, int r)//划分的随机版本
{
    int x = Rand(p,r);
    swap(A[r],A[x]);
    return Partition(A, p, r);
}
int RANDOMIZED_SELECT(int A[], int p, int r, int i)//基于循环版的randomized_select
{
    while (1)
    {
        if (p == r)
        {
            return A[p];
        }
        int q = Randmom_Partion(A, p, r);
        int k = q - p + 1;
        if (i == k)
        {
            return A[q];
        }
        else if (i<k)
        {
            r = q - 1;//这行代码可以处理有重复的待查找数。
            //q--;//网上给的答案是用这行,这行代码不能处理重复元素,例如int A[n]={63,34,92,34,44,16,2,39};需要找的第3小数刚好有重复数。
        }
        else
        {
            p = q + 1;
            i = i - k;
        }

    }
}
int Random_Select(int *A, int p, int r, int i)//随机选择
{
    if (p == r)
        return A[p];
    int q = Randmom_Partion(A,p,r);
    int k = q - p + 1;
    if (k == i)
        return A[q];
    else if (i < k)
        return Random_Select(A, p, q - 1, i);
    else
        return Random_Select(A, q + 1,r, i - k);//当在右侧时,注意修改下一次i值

}
int main()
{
    int A[] = { 63, 34, 92, 34, 44, 16, 2, 39};
    int N = sizeof A / sizeof A[0];
    srand((int)time(0));//必须放在调用前,不可放到产生随机数的函数中
    cout << RANDOMIZED_SELECT(A, 0, N - 1, 5) << endl;

}

 

转载于:https://www.cnblogs.com/liuhg/p/RANDOM_SELECT.html

### 线性时间选择算法的实现与原理 #### 1. 原理概述 线性时间选择算法的核心目标是从一个无序数组中高效地找出第 k 小的元素。它采用分治策略以及随机化技术来降低最坏情况下的时间复杂度,从而达到平均情况下 \(O(n)\) 的效率[^1]。 具体来说,该算法通过类似于快速排序中的分区操作(partition),将数组划分为两个部分:一部分小于选定的基准值(pivot),另一部分大于等于基准值。随后根据划分的结果调整搜索范围,逐步缩小问题规模直到定位到目标元素位置[^2]。 为了进一步优化性能并确保即使在极端条件下也能维持较好的表现,舍伍德型变种引入了随机选取基准的方法。这种方法不仅保留了良好的期望运行时间特性——即大多数时候能够保持接近理想的执行速度;而且有效规避了一些可能导致传统固定规则下退化至平方级耗时的情况发生[^4]。 #### 2. Python 实现示例 以下是基于上述理论构建的一个简单版本Python程序: ```python import random def linear_time_select(arr, order_statistic): if len(arr) == 1: return arr[0] pivot = random.choice(arr) lows = [el for el in arr if el < pivot] highs = [el for el in arr if el > pivot] pivots = [el for el in arr if el == pivot] if order_statistic < len(lows): # The desired element is in the 'lows' part. return linear_time_select(lows, order_statistic) elif order_statistic < len(lows) + len(pivots): # Found within duplicates of our chosen pivot value itself. return pivot else: # Must be inside higher values than current pivot then adjust index accordingly now searching there instead. new_order_statistic = order_statistic - len(lows) - len(pivots) return linear_time_select(highs, new_order_statistic) # Example usage: example_array = [7, 10, 4, 3, 20, 15] kth_smallest_element = 3 result = linear_time_select(example_array, kth_smallest_element-1) print(f"The {kth_smallest_element}rd smallest element is {result}.") ``` 这段代码定义了一个名为 `linear_time_select` 函数用于寻找指定顺序统计量对应的数值。其中运用到了列表推导式创建三个子集分别存储低于、高于及等于所选枢纽元的所有成员项,并依据比较结果决定下一步递归调用的方向或是直接返回匹配的答案。 #### 3. 关键点解析 - **随机化的重要性**: 使用随机数生成器挑选枢轴有助于平衡不同分布模式的数据集合处理效果,在理论上提供了更稳健的整体效能保障。 - **空间交换时间**: 虽然这里展示的是较为简洁直观的形式,但它涉及到额外内存消耗用来暂存分割后的各组数据副本。实际应用当中可能还需要考虑如何减少这种开销的影响因素。 - **边界条件管理**: 特别注意当请求超出合法索引界限或者传入空序列等情况时应妥善处置以免引发异常终止等问题出现。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值