Java selection Sort

Source: Internet
Author: User

Algorithm steps

Set the array to a[0...n-1].

1. initially, The array is all unordered area is a[0..n-1]. Make I=0

2. Select a minimal element in the unordered area a[i...n-1] and swap it with a[i]. After the exchange, a[0...i] formed an orderly area.

3. i++ and repeat the second step until the i==n-1. Sorting is Complete.

Algorithm diagram

Basic performance of the algorithm

Sorting methods Average situation Best case Worst case scenario Complexity of controls Stability
Select sort O (n2) O (n2) O (n2) O (1) Not stable

Java code

 packagecom.sort;Importjava.util.Random; public classMain3 {//from small to large    Private Static voidSortint[] Array) {        if(array.length <= 1) {            return; }         for(inti = 0; I < array.length-1; i++) {            intMin =i; /*** The subscript of the smallest element is found within the subscript range of the I+1~array.length-1*/             for(intj = i + 1; J < array.length; J + +) {                if(array[min] >Array[j]) {min=j; }            }            /*** If the smallest subscript changes, then the Exchange*/            if(min! =I) {inttemp =array[i]; array[i]=array[min]; array[min]=temp; }        }    }    /*** Gets a random array of the specified length*/     public Static int[] Getrandomarray (intN) {int[] array =New int[n]; Random Random=NewRandom ();  for(inti = 0; I < array.length; i++) {array[i]= Random.nextint (500); }        returnarray; }    /*** Print the specified array*/     public Static voidOutputarray (int[] Array) {         for(intI:array) {System.out.print (i+ " "); } System.out.println (""); }     public Static voidmain (string[] Args) {int[] array = Getrandomarray (10);        Outputarray (array);        Sort (array);    Outputarray (array); }}

Java selection 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.