Sort--Select sort

Source: Internet
Author: User

In a sorted family, choosing a sort is the simplest of all.

Its ideas (from small to Large):

    1. For a given set of records, after the first round of comparison, the minimum record is obtained, and then the record is exchanged with the position of the first record;
    2. Next the second round of records excluding the first record is obtained, and the minimum record is exchanged with the position of the second record;
    3. And so on, until all records are traversed.

Example:

Initialize: {5,1,2,4,3}

First round: {1,5,2,4,3}

Second round: {1,2,5,4,3}

Third round: {1,2,3,4,5}

Fourth round: {1,2,3,4,5}

Fifth round: {1,2,3,4,5}

You can see that the time complexity is 0 (N2), the space complexity 0 (1), the unstable sort, n is smaller when the performance is better.

Java Sample Code

 Public classSort { Public Static voidSelectsort (int[] a) {        intI, j, temp = 0, flag = 0, n =a.length;  for(i = 0; i < n; i++) {Temp=A[i]; Flag=i;  for(j = i+1; J < N; j + +) {                if(a[j]<temp) {Temp=A[j]; Flag=J; }            }            if(Flag! =i) {A[flag]=A[i]; A[i]=temp; }        }    }     Public Static voidMain (string[] args) {intA[] = {5,1,2,4,3};        Selectsort (a);  for(inti = 0; i < a.length; i++) {System.out.print (A[i]+ " ");    } System.out.println (); }}

Sort--Select sort

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.