Java Bubble sort (Bubble sort) instance explanation _java

Source: Internet
Author: User

Give an example: int[] array = {2,4,9,7,6,5};

The first round 2 and 4 are compared, 2<4, and the position is unchanged. Compare 4 and 9, 4<9, position unchanged. Again 9 and 7 are compared, and the 9>7,9 and the 7 positions are interchanged. Again 9 and 6 are compared, and the 9>6,9 and the 6 positions are interchanged. Compare 9 and 5, 9>5, position swap. The result of the first round comparison is 2 4 7 6 5 9.

The second round 2 and 4 are compared, 2<4, and the position is unchanged. Compare 4 and 7, 4<7, position unchanged. Again 7 and 5 are compared, and the 7>6,7 and the 6 positions are interchanged. Again 7 and 5 are compared, and the 7>5,7 and the 5 positions are interchanged. The result of the second round was 2 4 6 5 7 9.

Third Round 2 and 4 are compared, 2<4, position unchanged. Compare 4 and 6, 4<6, position unchanged. Again 6 and 5 are compared, and the 6>5,6 and the 5 positions are interchanged. The result of the third round was 2 4 5 6 7 9 (Already the result we wanted).

The code is as follows:

Copy Code code as follows:

Package com.test;

public class Bubblesorttest
{
public static void Main (string[] args)
{
Int[] array = {2,4,9,7,6,5};
bubblesorttest BST = new Bubblesorttest ();
Bst.bubblesort (array);
}

Public int[] Bubblesort (int[] array)
{
for (int i=0;i<array.length-1;i++)
{
Boolean BL = true;
for (int j=0;j<array.length-1-i;j++)
{
if (Array[j] > Array[j+1])
{
BL = false;
int temp = Array[j];
ARRAY[J] = array[j+1];
ARRAY[J+1] = temp;
}
}

If the wheel does not have a position change, the description has been sorted, there is no need to judge the
if (BL)
{
Break
}

/*--to view the results of the code, you can ignore the---------------------* *
System.out.println ("First" + (i + 1) + "trip sort");
for (int k = 0; k < array.length; k++)
{
System.out.print (Array[k] + "");
}
System.out.println ();
/*-------------------------------------*/

}
return array;
}

}

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.