Select, bubble, and insert sort

Source: Internet
Author: User

1. Select sorting

Thought: select the smallest (or largest) element from the data elements to be sorted for each trip, and place the order first (or last) of the sorted series ), until all data elements to be sorted are sorted. Analysis example:

 

 

 

 

 

 

 

 

 

 

 

 

The JAVA code is as follows:

Public static void selectSort (int [] ){

For (int I = 0; I <a. length-1; I ++ ){
For (int j = I + 1; j <a. length; j ++ ){
If (a [I] <a [j]) {
Int temp = a [I];
A [I] = a [j];
A [j] = temp;
}
}
}
System. out. println (Arrays. toString ());
}

 

 

 

2. Bubble Sorting

Thought: (1) Compare adjacent elements. If the first is bigger than the second, exchange the two of them.

(2) perform the same operation on each adjacent element, starting from the first pair to the last one.

(3) Repeat the preceding steps for all elements except the last one.

(4) continue to repeat the above steps for fewer and fewer elements until there is no need to compare any number.

The JAVA code is as follows:

Public static void bubbleSort (int [] ){

For (int I = 0; I <a. length-1; I ++ ){
For (int j = 0; j <a. length-i-1; j ++ ){
If (a [j] <a [j + 1]) {
Int temp = a [j];
A [j] = a [j + 1];
A [j + 1] = temp;
}
}
}
System. out. println (Arrays. toString ());
}

 

3. Insert sorting

Thought: each step inserts a data to be sorted to an appropriate position in the sorted data according to its size until all data is inserted.

JAVA code implementation:

Public static void insertionSort (int [] ){

For (int I = 1; I <a. length; I ++ ){
Int temp = a [I]; // Save the element to be inserted
Int j = 0;
For (j = I-1; j> = 0; j --){
If (temp <a [j]) {// compare the elements to be inserted with the sorted Elements
A [j + 1] = a [j]; // move large elements behind
} Else {
Break; // indicates that the first I elements are already in order, that is, the insertion position has been found.
}
}
A [j + 1] = temp;
}
System. out. println (Arrays. toString ());
}

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.