Quick Sorting and quick selection (Java)

Source: Internet
Author: User

Quick selection can be in the time complexity of the NLOGN to get a set of unordered number of the K large, based on a quick ordering, each time a number for the midpoint divided into the left and right two segments, the left is less than equal to the number of partitions, and the rights are greater than equal to the number of split, the fast choice of the solution faster than all sorts

/** * Created by Tcgogogo on 16/8/18. */class Solution {public void OutPut (int[] nums) {for (int i = 0; i < nums.length; i++) {System        . Out.print (Nums[i] + "");    } System.out.println ();        } public void Swap (int[] nums, int i, int j) {if (i = = j) {return;        } int tmp = Nums[i];        Nums[i] = Nums[j];    NUMS[J] = tmp;        } public void QuickSort (int[] nums, int. left, int. right) {if (left > right) {return;        } int i = left and j = right;            while (I < J) {while (I < J && Nums[j] >= Nums[left]) {J--;            } while (I < J && Nums[i] <= Nums[left]) {i + +;            } if (I < j) {Swap (Nums, I, J);        }} swap (Nums, left, i);        QuickSort (Nums, left, i-1);    QuickSort (Nums, i + 1, right); } public int Quickselect (int[] nums, int left, int. right, int k) {if (left > right) {return 0;        } int i = left and j = right;            while (I < J) {while (I < J && Nums[j] >= Nums[left]) {J--;            } while (I < J && Nums[i] <= Nums[left]) {i + +;        } swap (Nums, I, J);        } swap (Nums, left, i);        if (k = = I-left + 1) {return nums[i];        } else if (K < I-left + 1) {return Quickselect (Nums, left, i-1, K);        } else {return quickselect (nums, i + 1, right, K-(I-left + 1)); }    }}


Quick Sorting and quick selection (Java)

Related Article

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.