插入排序的变体——冒泡排序

上一篇博文说到了插入排序,如果我将内循环中的较大元素都向右移动,而不是总是两两之间进行交换。这个把较大元素不断上浮的算法就是大家经常说的冒泡排序

 1 public class BubbleSort
 2 {
 3     public static void sort(int[] a)
 4     {
 5         int N = a.length;
 6         int count = 0;
 7         for (int k = 1; k < N; k++)
 8         {
 9             for (int i = 1; i < N; i++)        // 只有这句话与插入排序不同
10             {
11                 if (a[i] < a[i-1])
12                 {
13                     int temp = 0;
14                     temp = a[i];
15                     a[i] = a[i-1];
16                     a[i-1] = temp;
17                     count++;
18                 }
19             }
20         }
21         
22         for (int i = 0; i < N; i++)
23             System.out.print(a[i] + " ");
24         System.out.println("count = " + count);
25     }
26     
27     public static void main(String[] args)
28     {
29         int[] a = {6, 2, 5, 3, 1, 4};
30         BubbleSort.sort(a);
31     }
32 }

 

posted @ 2014-05-15 21:23  owen-beta  阅读(211)  评论(0编辑  收藏  举报