2.5 排序应用之“找到第k小的数或中位数”

本文介绍了一种利用快速排序的partition函数实现寻找数组中第K小元素的算法。通过分区将数组分为两部分,递归地在所需部分中查找目标元素,提高了查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书中第221页。

采用的是快排中的partition函数来帮助

package com.Page1;

import edu.princeton.cs.algs4.StdRandom;

public class Kmin { //找到第k小的元素,即比它小的元素有k个
	
	private static int partition(Type[] a,int lo,int hi)
    {
   	 Type x=a[lo];
   	 int i=lo;
   	 int j=hi+1;
   	while(true)
   	{
   		while(less(a[++i],x)) if(i==hi) break;
   		while(more(a[--j],x)) if(j==lo) break;
   		if(i>=j) break;
   		exch(a,i,j);
   	}
   	exch(a,lo,j);//注意不是i而是j	 
   	return j;
    }
	
	public static void exch(Type[] a,int i,int j)
    {
   	 Type x=a[i];
   	 a[i]=a[j];
   	 a[j]=x;
    }
	
	public static boolean less(Type x,Type y)
    {
   	 if(x.key.compareTo(y.key)==-1) //若是小于或等于,则返回true
   		 return true;
   	 else
   		 return false;
    }
	
	public static boolean more(Type x,Type y)
    {
   	 if(x.key.compareTo(y.key)==1) //若是小于或等于,则返回true
   		 return true;
   	 else
   		 return false;
    }
	
	public static Type findKmin(Type[] a,int k,int lo,int hi)
	{
		if(lo>=hi) return a[lo];
		int i=partition(a,lo,hi);
		if(i==k) return a[i];
		else if(i>k) return findKmin(a,k,lo,i-1);
		else return findKmin(a,k-i-1,i+1,hi);
	}
	
	public static void main(String[] args)
	{
		Type[] a=new Type[5];
		a[0]=new Type(6);
		a[1]=new Type(1);
		a[2]=new Type(1);
		a[3]=new Type(2);
		a[4]=new Type(3);
		StdRandom.shuffle(a);//打乱先
		Type result=findKmin(a,2,0,a.length-1);
		System.out.println(result.key);
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值