Find the number of the K-large in an array

Source: Internet
Author: User

Quick line idea, select the sequence of a key to divide, less than key on the left, greater than the key on the right, the position of key-low+1 is the last element is the number of elements in the sequence of key, when the number of elements greater than k, in the left half of the recursive search, equal to Arr[key] is the K

Large element, less than K, recursively finding the K-num large element on the right

/** * File name: Findk.java * Time: November 7, 2014 11:23:43 * Xiu Kang */package chapter7;/** * class Name: FINDK Description: Found an array of K-Large elements */public class Fin DK {public static int partition (int[] A, int. low, int.) {int key = A[low];while (Low < High) {when (Low < high && A[high] >= key) High--;a[low] = A[high];while (Low < high && A[low] <= key) Low++;a[high] = A[lo W];} A[low] = Key;return low;} public static int Quickselect (int[] A, int. low, Int. High, Int. K) {if (low = = high) return a[low];int Keypos = partition (A, Low, high); int num = Keypos-low + 1;if (num = = k) return A[keypos];else if (K < num) return Quickselect (A, low, keypos -1, k); Elsereturn Quickselect (A, Keypos + 1, high, k-num);} /** * Method Name: Main Description: Test */public static void Main (string[] args) {//TODO auto-generated method stubint[] A = new int[] {1, 2, 3,4,5,6,7,8,9,10}; System.out.println (Quickselect (A, 0, a.length-1,5));}}


Find the number of K in an array

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.