线性时间选择:求数组中第n小的值
一:
解决的方法是基于快速排序解决的,当快速排序进行一次排序的时候,在参考点左侧的都是比参考值小的,右侧都是比参考点大的。
(1)参考点的下标等于 n-1,说明参考点就是第n小的值。
(2)参考点的下标大于n-1 , 说明所要求得第n小的值在参考值左侧的数组里,只需要对左侧数组进行快速排序。
(3)参考点的下标小于n-1,说明所要求的第n小的值在参考值右侧的数组里,只需要对右侧数组进行快速排序。
二:
程序如下:
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <time.h>
#include <stdlib.h>
#define LENGTH 10
using namespace std;
template <class Type>
void swap(Type *a,Type *b){
Type c;
c = *a;
*a = *b;
*b = c;
}
template <class Type>
Type QuickSort(Type a[],int l,int r,int n){ //排序从l到r的数组
if(l < r){ // 如果l >= r 不进行操作
int t = l;
int stl = l; //stl为左侧的指针
int str = r+1; //str为右侧指针
while(true){
while(a[++stl] <= a[t] && stl &

本文介绍了如何在线性时间内找到数组中第n小的元素,方法基于快速排序的分治策略。通过确定参考点与n的关系,递归地在相应区间进行查找,确保在平均情况下保持线性时间复杂度。
&spm=1001.2101.3001.5002&articleId=83314352&d=1&t=3&u=b2ac4ce6663240aca63e2595714bbb96)
4811

被折叠的 条评论
为什么被折叠?



