使用Java查找第k个最小元素

时间:2015-04-05 05:53:15

标签: java recursion partition

我正在尝试使用分区创建用于查找k th 最小元素的代码。

当我运行此代码时,我认为它对于少于5个数字非常好,但每当我使用更大的数据时 - 比如超过100或10000个数据 - 并尝试找到k th 号码,它不断给我回复java.lang.StackOverflowError消息,或者只是完成错误的答案。

这是我的代码:

import java.util.Scanner; 

public class test2 {        

    public static int partition(double arr[], int begin, int end){          

        int pivotIndex = begin; 
        double pivot = arr[pivotIndex];                 
        begin++; 

        int p = begin; 
        int r = (int) end; 
        while (p <= r){
            while (p <= r && arr[p] < pivot)
                p++; 

            while(p<=r && arr[r] > pivot)
                r--;            
            if (p > r){
                swap(arr, pivotIndex, r);} 
            else {swap(arr, p, r);
            }               
            }
        return r;}              
    public static void swap(double[] arr, int a, int b){        

          if (a <= b){  
            double temp;
            temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;  }           
    }       

    public static double selection(double[] arr, int begin, int end, int k){

        int pivotIndex = begin; 
        int i = pivotIndex; 
        pivotIndex = partition(arr, begin, end); 


        if (i == k-1){
            return arr[(k-1)]; 

        }
        else if (i > k-1 ){ 
            return selection(arr, begin, i-1, k); 
        }
        else{

            return selection(arr, i+1, end, k-i);   }}          


    public static void main (String[] args) {


        Scanner scan = new Scanner(System.in); 
        System.out.println("Selection Test\n"); 
        int n, i; 

        System.out.println("Enter number of elements"); 
            n = scan.nextInt(); 

        double arr[] = new double [n]; 


       System.out.println("\nEnter "+ n +" elements");
            for (i = 0; i < n; i++)   


            arr[i] = scan.nextDouble();         
            System.out.println("\nEnter the kth smallest element you'd like to find");   
            int k = scan.nextInt();

            kthsmall(arr, k);

             System.out.println(arr[k-1
                                    ]);          

    }       
    public static void kthsmall(double[] arr, int k){
        selection(arr, 0, arr.length -1, k);}

如果有人能告诉我我的错误在哪里,我真的很感激。

0 个答案:

没有答案