After getting this question, you will first think of sorting. After sorting, select the largest K number. Sorting selection Quick sort is a better choice.
Okay, let's do the first solution: quick sort
The code is as follows
Copy the code code as follows:
public static void quickSort(int[] arr, int start, int end) {
if (start < end) {
int key = arr[start];
int right = start;
int left = end;
while (right < left) {
while (right < left && arr[left] > key) {
left --;
}
if (right < left) {
arr[right] = arr[left];
}
while (right < left && arr[right] <= key) {
right++;
}
if (right < left) {
arr[left] = arr[right];
}
}
arr[right] = key;
quickSort(arr, start, right-1);
quickSort(arr, left+1, end);
}
}
After quick sorting, the array will be in order. The above sorting is from small to large, so our output should be as follows
Copy the code as follows: int k = 4;
for (int i=arr.length-1; i>=arr.length-k; i--) {
System.out.println(arr[i]+" ");
}
. The first solution is already good, but is there a better way?
The answer is yes! We can choose partial sorting, and then we use selection sorting to solve this problem.
The code is as follows:
Copy the code as follows: public static int[] selectSortK(int[] arr, int k) {
if(arr == null || arr.length == 0) {
return null;
}
int[] newArr = new int[k];
List<Integer> list = new ArrayList<Integer>();//Record the subscript of the maximum number each time
for (int i=0; i<k; i++) {
int maxValue = Integer.MIN_VALUE; //Maximum value
int maxIndex = i;
for (int j=0; j<arr.length; j++) {
if (arr[j] > maxValue && !list.contains(j) ) {
maxValue = arr[j];
maxIndex = j;
}
}
if (!list.contains(maxIndex)) {//If it does not exist, add it
list.add(maxIndex);
newArr[i] = maxValue;
}
}
return newArr;
}