寻找最大的第K个数

来源:互联网 发布:淘宝网有没有海外版 编辑:程序博客网 时间:2024/04/30 16:36

题目:

给定一个数组 如{1,2,3,4,5,6,7,8}

求第四大的数是 key = 4;

对于此类求第几大的数的问题,一般建议用堆排序,并不需要对整个数组进行排序。

import java.util.*;public class MaxKnum{public static int[] s;public static void main(String[] args){System.out.println("Enter an array[10]");Scanner sc = new Scanner(System.in);s = new int[10];for(int i=0;i<10;i++){s[i] = sc.nextInt();}System.out.println("you want find which largest?:");int index = sc.nextInt();int key = findMaxK(index-1,s,0,9);System.out.println("the fourth largest is "+key1);}public static int findMaxK(int keyIndex,int[] s,int begin,int end){if(keyIndex>end||keyIndex<begin)return -1;int pos1 = begin;int pos2 = end;int pivotkey = s[begin];while(pos1<pos2){while(pos1<pos2&&s[pos2]>=pivotkey)pos2--;swap(pos1,pos2);while(pos1<pos2&&s[pos1]<=pivotkey)pos1++;swap(pos1,pos2);}if(pos1==keyIndex)return s[keyIndex];else if(pos1>keyIndex)return findMaxK(keyIndex,s,begin,pos1-1);elsereturn findMaxK(keyIndex,s,pos1+1,end);}public static void swap(int i,int j){int temp = s[i];s[i] = s[j];s[j] = temp;}}


原创粉丝点击