-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathFindTopKNumbers.java
More file actions
33 lines (29 loc) · 887 Bytes
/
FindTopKNumbers.java
File metadata and controls
33 lines (29 loc) · 887 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package by.andd3dfx.sorting;
import java.util.Arrays;
/**
* Find top k numbers in array
*
* @see <a href="https://youtu.be/iBOodbu0wKQ">Video solution</a>
*/
public class FindTopKNumbers {
/**
* We use short version of selection sort algorithm with O(kn) complexity
*/
public static int[] find(int[] array, int k) {
for (int i = 0; i < k; i++) {
int maxElementIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] > array[maxElementIndex]) {
maxElementIndex = j;
}
}
swap(array, i, maxElementIndex);
}
return Arrays.copyOf(array, k);
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}