Finding k largest (or smallest) elements in an array 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 &lt; 0 || k &gt; array.length){
        return;
    }       
    int[] temp = new int[k];        

    for(int i = 0; i &lt; k; i++){
        temp[i] = array[i];
    }       
    for(int i = k; i &lt; array.length; i++){  
        int min = Integer.MAX_VALUE;
        int minIndex = 0;
        for(int j = 0; j &lt; temp.length; j++){               
            if(temp[j] &lt; min){
                min = temp[j];
                minIndex = j;
            }
        }   
        if(array[i] &gt; min){
            temp[minIndex] = array[i];  
        }
    }
    for(int i : temp){
        System.out.print(i + " ");
    }
}
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 &lt; array.length; i++){
        minIndex = 0;
        for (int j = 0; j &lt; k; j++){
            if(array[j] &lt; array[minIndex]){
                minIndex = j;
                array[minIndex] = array[j];
            }
        }       
        if (array[minIndex] &lt; array[i]){         //Swap item if min &lt; array[i]

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