zoukankan      html  css  js  c++  java
  • 减治算法之寻找第K小元素问题

    一、问题描写叙述

    给定一个整数数列,寻找其按递增排序后的第k个位置上的元素。

    二、问题分析

    借助类似快排思想实现pation函数。再利用递归思想寻找k位置。

    三、算法代码

    public static int selectMinK(int [] arr, int low, int high, int k){
    		int index = pation(arr, low, high);
    		if(index == k){
    			return arr[index];
    		}
    		if(index < k){
    			return selectMinK(arr, index + 1, high, k);
    		}else{
    			return selectMinK(arr, low, index - 1, k);
    		}
    	}
    	
    	public static int pation(int [] arr, int low, int high){
    		while(low < high){
    			while(low < high && arr[low] <= arr[high]){//从后往前。把小的元素往前调换
    				high--;
    			}
    			if(low < high){
    				int tmp = arr[low];
    				arr[low] = arr[high];
    				arr[high] = tmp;
    				low++;
    			}
    			while(low < high && arr[low] <= arr[high]){//从前往后。把大的元素往后调换
    				low++;
    			}
    			if(low < high){
    				int tmp = arr[low];
    				arr[low] = arr[high];
    				arr[high] = tmp;
    				high--;
    			}
    		}
    		return low;//返回low。high相遇位置
    	}
    四、完整測试代码

    public class Solution {
    	
    	public static void main(String [] args){
    		int [] randArr = new int[]{5,2,8,6,3,6,9,7};
    		int result = selectMinK(randArr, 0, randArr.length - 1, 4);
    		System.out.print(result);
    	}
    	public static int selectMinK(int [] arr, int low, int high, int k){
    		int index = pation(arr, low, high);
    		if(index == k){ //若返回的下标为k,则找到目标元素
    			return arr[index];
    		}
    		if(index < k){
    			return selectMinK(arr, index + 1, high, k);
    		}else{
    			return selectMinK(arr, low, index - 1, k);
    		}
    	}
    	
    	public static int pation(int [] arr, int low, int high){
    		while(low < high){
    			while(low < high && arr[low] <= arr[high]){
    				high--;
    			}
    			if(low < high){
    				int tmp = arr[low];
    				arr[low] = arr[high];
    				arr[high] = tmp;
    				low++;
    			}
    			while(low < high && arr[low] <= arr[high]){
    				low++;
    			}
    			if(low < high){
    				int tmp = arr[low];
    				arr[low] = arr[high];
    				arr[high] = tmp;
    				high--;
    			}
    		}
    		return low;
    	}
    }
    
    五、执行结果

    第4小元素为:6




  • 相关阅读:
    链接
    列表
    Android Studio AVD 虚拟机 联网 失败
    docker error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.29/containers/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuratio
    JSP Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
    js jsp form
    intellij jsp 中文乱码
    [转载]在Intellij Idea中使用JSTL标签库
    windows pybloomfilter
    docker mysql
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7168608.html
Copyright © 2011-2022 走看看