Java sorting algorithm: the algorithm implementation of bubble sort (code)

Source: Internet
Author: User
This article brings to you the content is about the Java sorting algorithm: Bubble sorting algorithm Implementation (code), there is a certain reference value, the need for friends can refer to, I hope you have some help.

Bubble Sort method is one of the most basic sorting methods, and the mechanism of bubble sorting is a simple sort method which is implemented by iterating through elements and adjusting the order of neighboring elements. The essence of the bubbling sort is the comparison of the adjacent two elements, and then the position is swapped in ascending or descending order.

Below is the code for descending bubble sort:

public class Training {public static void main (string[] args) {        int [] array = {3,2,5,1,4};for (int time = 1; looptime < Array.Length; looptime++) {for (int i = 0,temp = 0; i < array.length-looptime; i++) {if (Array[i+1]>array[i]) {temp = Array[i+1];a RRAY[I+1] = array[i];array[i] = temp;}}} for (int i = 0; i < Array.Length; i++) {System.out.println (array[i]);}}}    

the for The loop will place large data in the appropriate position once per cycle, such as Looptime =1 to put the maximum data in the last ; Looptime =2 ; Place the second largest data in the second-to-last element position; Array.length-looptime : from the aspect of improving the performance of the code, the number of cycles of "redundant" loops is reduced.

The following is the result of the operation:

Of course, there is an ascending sort of bubble, in fact, only the "if (Array[i+1]>array[i])" In the Boolean condition is changed to array[i+1]<array[i] can.

for (int i = 0; i < array.length-time; i++) {if (Array[i+1]<array[i]) {temp = a RRAY[I+1];ARRAY[I+1] = array[i];array[i] = temp;}} 
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.