Using Java to implement bubble sort method

Source: Internet
Author: User

First, the basic idea:

Bubble sort is a simple sort of exchange class. The basic idea 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 large key values back. After each pass, the element with the highest key value is moved to the end, where the element's position is noted, and the next order only needs to be compared to this location until all the elements are sorted in an orderly manner.

Generally, the n elements are bubbled up, and a total of n-1 is required. The 1th trip needs to compare n-1 times, 2nd trip needs to compare n-2 times, ... The first trip needs to be compared n-i times.

Second, the implementation of the algorithm

public class bubblesort{

public static void Main (String args[]) {

Int[] values={3,1,6,2,9,0,7,4,5};

Sort (values);

for (int i=0;i<values.length;i++) {//The elements in the print group after sorting

System.out.println ("Index:" +i+ "value:" +values[i]);

}

}

public static void sort (int[] values) {

int temp;

for (int i=0;i<values.length;i++) {//Number of times

for (int j=0;j<values.length-i-1;j++) {//Number of comparisons

if (Values[j]>values[j+1]) {

TEMP=VALUES[J];

VALUES[J]=VALUES[J+1];

Values[j+1]=temp;

}

}

}

}

}

Using Java to implement bubble sort method

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.