New school Bubble sorting, New School Bubble Sorting

Source: Internet
Author: User
Tags rounds

New school Bubble sorting, New School Bubble Sorting

 

Import java. util. collections;

Public class MaoPaoPaiXu {

Public static void main (String [] args ){
Scanner input = new Scanner (System. in); // create a Scanner
System. out. print ("array length :");
Int num = input. nextInt (); // enter the array length on the keyboard.
Int [] nums = new int [num]; // defines an array
Int I, j; // defines two cyclic Variables
Int temp; // Temporary Variable
For (int k = 0; k <nums. length; k ++ ){
System. out. print ("th" + (k + 1) + "number :");
Nums [k] = input. nextInt ();
}
System. out. print ("Before sorting :");
For (int k = 0; k <nums. length; k ++ ){
System. out. print (nums [k] + "");
}
/**
* Bubble Sorting (Dual Loop)
*/
For (int k = 0; k <nums. length-1; k ++) {// control how many rounds are compared
For (int k2 = 0; k2 <nums. length-1-k; k2 ++) {// change the largest element to the last
If (nums [k2]> nums [k2 + 1]) {
// Exchange Element
Temp = nums [k2];
Nums [k2] = nums [k2 + 1];
Nums [k2 + 1] = temp;
}
}
}
System. out. print ("\ n after sorting :");
For (int k = 0; k <nums. length; k ++ ){
System. out. print (+ nums [k] + "");
}
}
}

Bubble Sorting is actually a simple exchange sorting. It is to scan the elements to be sorted from the beginning, compare the Adjacent Elements in sequence during the scanning process, and move the elements with a large keyword value behind. After each sorting, the element with the maximum keyword value will be moved to the end. At this time, write down the position of the element. The next sorting only needs to be compared to this position, until all elements are sorted.

Simply put:

It is to execute a double loop. The number of rounds of comparison is the condition of the outer loop, and the number of comparisons is the condition of the inner loop.

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.