HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Finding k largest (or smallest) elements in an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
smallestelementsarraylargestfinding

Problem

I have written this code for the question:


Finding k largest (or smallest) elements in an array

My approach uses a temporary array. Please suggest any improvements for readability or better performance.

public static void kLargest(int[] array, int k){

    if(k  array.length){
        return;
    }       
    int[] temp = new int[k];        

    for(int i = 0; i  min){
            temp[minIndex] = array[i];  
        }
    }
    for(int i : temp){
        System.out.print(i + " ");
    }
}

Solution

You can write it without extra space and with one less variable. Instead of considering a new array (temp array), do all the swap in the original array; in this case, you will skip O(k) extra space. Also, there is no need to keep track of min value. Keep tracking of min index and update it in every round will be enough.

public static void kLargest2(int[] array, int k){

    int minIndex = 0, i;                            //Find Min

    for (i = k; i < array.length; i++){
        minIndex = 0;
        for (int j = 0; j < k; j++){
            if(array[j] < array[minIndex]){
                minIndex = j;
                array[minIndex] = array[j];
            }
        }       
        if (array[minIndex] < array[i]){         //Swap item if min < array[i]

            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
        }
    }
    for (int q = 0; q < k; q++){                            //Print output
        System.out.print(array[q] + " ");
    }
}

Code Snippets

public static void kLargest2(int[] array, int k){

    int minIndex = 0, i;                            //Find Min

    for (i = k; i < array.length; i++){
        minIndex = 0;
        for (int j = 0; j < k; j++){
            if(array[j] < array[minIndex]){
                minIndex = j;
                array[minIndex] = array[j];
            }
        }       
        if (array[minIndex] < array[i]){         //Swap item if min < array[i]

            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
        }
    }
    for (int q = 0; q < k; q++){                            //Print output
        System.out.print(array[q] + " ");
    }
}

Context

StackExchange Code Review Q#98010, answer score: 4

Revisions (0)

No revisions yet.