Sorting Algorithm (1) Select sorting

Source: Internet
Author: User

Select Sorting Algorithm: (small to large sorting)

1. traverse the set from start to end in sequence

2. Each time the smallest element in the remaining part is mentioned at the beginning.

 

The implementation code is as follows:

[Html]
Package com. robert. paixu;
 
// Sorting Algorithm
Public class SortAlgorithm {

Public static void main (String [] args ){
// Sort by the selected Sorting Algorithm
Int [] numbers = {20,190,120, 50,130 };
SelectSort (numbers );
Display (numbers );
}

/**
* Select sorting
* Sorting from small to large
*/
Private static void selectSort (int [] arrays ){
For (int I = 0; I <arrays. length-1; I ++)
{
// Obtain the lowest element subscript
Int indexSmallest = getIndexOfSmallest (arrays, I );
If (arrays [indexSmallest] <arrays [I])
{
// Exchange Element
Swap (arrays, I, indexSmallest );
}
}
}
 
 
/**
* Starting from an index, retrieve the index of the smallest number in the remaining array.
* @ Param arrays
* @ Param I
* @ Return
*/
Private static int getIndexOfSmallest (int [] arrays, int I ){
Int smallFlag = I + 1;
For (int j = I + 1; j <arrays. length; j ++)
{
If (arrays [smallFlag]> arrays [j])
{
SmallFlag = j;
}
}
Return smallFlag;
}
/**
* @ Param arrays the array to be exchanged
* @ Param index1 element 1 subscript to be exchanged
* @ Param index2 element 2 subscript to be exchanged
*/
Private static void swap (int [] arrays, int index1, int index2)
{
Int temp = 0;
Temp = arrays [index1];
Arrays [index1] = arrays [index2];
Arrays [index2] = temp;
}

Private static void display (int [] arrays)
{
For (int I = 0; I <arrays. length; I ++)
{
System. out. print (arrays [I] + "");
}
}




}

The output result is as follows:

-50-20 0 1 2 3 4 6 7 8 9 10 11 12 20 120 130 190

 

The time complexity of the algorithm is O (n ^ 2) at any time)

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.