After this problem get the first thought of the sort, after the order in the selection of the maximum number of K. Sorting a quick sort selection is a better choice.
Okay, let's do the first solution: Quick sort
The code is as follows
Copy 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 a quick sort, the array will be ordered, the order above is small to large, so our output should be the following
Copy Code 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 good, but there is no better way.
The answer is YES! We can select the partial sort, and then we use the selection sort to solve the problem.
The code is as follows:
Copy Code 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> ()//subscript for maximum number per 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 not present, join
List.add (Maxindex);
Newarr[i] = MaxValue;
}
}
return NEWARR;
}