jnslee311
jnslee311

Reputation: 21

Returning the K biggest element from an array. (JAVA)

public static Word[] simpleSelect(Word[] array, int k){
    k= array.length;
    for(int i = 0; i< k-1; i++){
        for(int j = 0; j<k-i-1; j++){
            if(array[j].compareTo(array[j+1]) < 0){
                swap(array,j, j+1); 
            }
        }           
    }
    return array;
}

I created this above code to return the K biggest elements from an array through a bubble sort. I am suppose to make this method O(nk). I have wrote this code and figured that the returned array doesn't print an array with k size. Instead, it just prints the original array with the same length, just bubble sorted.

For example, if I my original array is {1,19, 7 ,26 ,9 ,85} and my k value is 2, I want it to return {85,26}. Instead, currently this code is returning {85,26,19,9,7,1} no matter what the k value is.

I would like to know what i am doing wrong here and also would like to know if I am coding right in O(nk) times.

Upvotes: 1

Views: 138

Answers (2)

Peekaboo
Peekaboo

Reputation: 141

  1. k is re-assigned on line 2: k = array.length; it's the reason why the method behaves regardless of the value of k.
  2. As for complexity bubble sort has an average complexity of O(n^2), it must be adapted to meet your O(nk) requirements.

Upvotes: 1

Joris Schellekens
Joris Schellekens

Reputation: 9012

Assume we have the following array of numbers

static int[] arr = {456, 12 , 998, 546, 12,  987, 6456, 66, 9789};

We are going to construct the array of k largest numbers by iteratively finding the largest number of the array and then marking that number so that it does not get picked again.

This is the method that will find the k largest elements:

private static int[] kLargest(int[] arr, int k){
    int[] klargest = new int[k];
    for(int i=0;i<k;i++){
        klargest[i] = findAndMarkLargest(arr);
    }
    return klargest;
}

And this is the method that find the single largest element, and then marks it (by setting the elements to Integer.MIN_VALUE)

private static int findAndMarkLargest(int[] arr){
    int largest = Integer.MIN_VALUE;
    for(int i=0;i<arr.length;i++){
        if(arr[i] > largest){
            largest = arr[i];
        }
    }
    for(int i=0;i<arr.length;i++){
        if(arr[i] == largest){
            arr[i] = Integer.MIN_VALUE;
        }
    }
    return largest;
}

The main method (that simply calls the kLargest method) looks like this:

public static void main (String[] args) throws java.lang.Exception
{
    // your code goes here
    System.out.println(Arrays.toString(kLargest(arr, 3)));
}

And outputs:

[9789, 6456, 998]

Each call to findAndMarkLargest takes 2*n operations (since it runs over the array twice).

The method findAndMarkLargest is called k times by 'kLargest'. So, in terms of big O notation, this is O(2kn) which is equivalent to O(nk)

Upvotes: 0

Related Questions