Finding the largest K-number solution in Java _java

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.