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;
}
}