转载出自:http://blog.csdn.net/wentasy/article/details/7438139
冒泡排序的关键点是从后向前对相邻的两个数组元素进行比较,若后面元素的值小于前面元素的值,则将这两个元素交换位置,否则不进行交换。依次进行下去,第一趟排序可将数组中值最小的元素移至下标为0的位置。对于有n个元素的数组,循环执行n-1趟扫描便可完成排序。(当然,也可以从前向后对相邻的两个数组元素进行比较,但此时应注意将大数向后移,与小者前移的冒泡法相对应,可将这种大者后移的排序称为下沉法)。
下图演示了有6个元素的数组实施冒泡法排序(小数前移)的前两趟比较与交换过程。可以看出,第一趟排序后最小数12已移到了下标为0的正确位置;第二趟排序后次小数17移到了下标为1的正确位置。
代码实现:
- public class BubbleSort{
- public static void main(String[] args){
- int a[] = {1, 23, 45, 6, 0, 99, 100, 89, 34, 56};
- System.out.println("排序前:");
- for (int i = 0; i < a.length; ++ i)
- System.out.print(a[i] + " ");
- bubbleSort(a);
- System.out.println();
- System.out.println("排序后:");
- for (int i = 0; i < a.length; ++ i)
- System.out.print(a[i] + " ");
- }
- public static void bubbleSort(int a[]){
- int temp = 0;
- for (int i = 0; i < a.length - 1; ++ i){
- for (int j = i; j < a.length; ++ j){
- if (a[i] > a[j]){
- temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
- }
- }
- }
- }
执行效果如图: