洛谷P1923 【深基9.例4】求第 k 小的数(java)

java 复制代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Scanner;
//输入n个数字ai,输出这些数字的第k小的数。最小的数是第0小。
public class Main {

    public static void main(String[] args) throws IOException {
        StreamTokenizer sc = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        sc.nextToken();
        int n = (int) sc.nval;
        sc.nextToken();
        int k = (int) sc.nval;
//        Scanner sc = new Scanner(System.in);
//        int n = sc.nextInt();//n个数
//        int k = sc.nextInt();//第k小的数
        int a[] = new int[n];
        for (int i = 0; i < n; i++) {
            sc.nextToken();
            a[i] = (int) sc.nval;
        }

        for (int i = 0; i < a.length; i++) {
            for (int j = i; j < a.length; j++) {

            }
        }
        //Quick_sort(a, 0, a.length - 1);
        //System.out.println(a[k]);o(nlogn)
        int i = find(a, 0, a.length - 1, k);

    }
     public static int find (int[] a,int left, int right, int k)
    {	//在数组a的第left到right中寻找第k小的数
        int tem=Partition(a,left,right);
        if(k==tem)
            System.out.println(a[k]);
        else if(k-1<tem)//判断下一次划分在哪一区间进行
            find(a,left,tem-1,k);
        else
            find(a,tem+1,right,k);
        return 0;
    }

    public static void Quick_sort(int[] a, int low, int high) {
        if (low < high) {
            int p = Partition(a, low, high);
            Quick_sort(a, low, p - 1);
            Quick_sort(a, p + 1, high);
        }

    }

    public static int Partition(int[] a, int low, int high) {
        int pivot = a[low];//pivot 支点;中心
        while (low < high) {
            while (low < high && a[high] >= pivot)
                high--;
            a[low] = a[high];
            while (low < high && a[low] <= pivot) low++;
            a[high] = a[low];
        }
            a[low] = pivot;
            return low;//return high
    }
}
相关推荐
你撅嘴真丑14 分钟前
第八章 - 贪心法
开发语言·c++·算法
VT.馒头19 分钟前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
wanghu202420 分钟前
AT_abc443_C~E题题解
c语言·算法
思想在飞肢体在追21 分钟前
Springboot项目配置Nacos
java·spring boot·后端·nacos
cyforkk23 分钟前
09、Java 基础硬核复习:异常处理(容错机制)的核心逻辑与面试考点
java·数据库·面试
梵刹古音24 分钟前
【C语言】 浮点型(实型)变量
c语言·开发语言·嵌入式
历程里程碑25 分钟前
Linux 17 程序地址空间
linux·运维·服务器·开发语言·数据结构·笔记·排序算法
u01092727128 分钟前
模板元编程调试方法
开发语言·c++·算法
??(lxy)44 分钟前
java高性能无锁队列——MpscLinkedQueue
java·开发语言
数研小生1 小时前
Full Analysis of Taobao Item Detail API taobao.item.get
java·服务器·前端