冒泡排序
1、原理:每一次循环都两两比较,直到最后,如下图就是两次循环的比较方式
(以上图片网络借用)
2、代码:
public class BubbleSortTest
{//冒泡排序法
public static void bubbleSort(int[] a)
{
for(int i = 0; i < a.length - 1; i++)//没循环一次就少一个数
{
for(int j = 0; j < a.length - i - 1; j++)
{
if(a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
System.out.println("第" + (i + 1) + "趟排序");
for(int k = 0; k < a.length; k++)
{
System.out.print(a[k] + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
int[] array = {4,7,8,9,3,2};
bubbleSort(array);
/*
for(int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
*/
}
}