统计信息

  • 访问数:8747
  • 博客数:142
  • 建立时间:2008-01-05
  • 更新时间:2008-05-21
我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!

P6Q17

2008-04-17 13:56:50

天气: 晴朗 心情: 高兴

/*filename:P6Q17
 *Name:Wang Chaoran
Description:
(Bubble sort) Write a sort method that uses the bubble-sort algorithm.
The bubble-sort algorithm makes several passes through the array. On each pass,
successive neighboring pairs are compared. If a pair is in decreasing order,
its values are swapped; otherwise, the values remain unchanged.
The technique is called a bubble sort or sinking sort because the smaller
values gradually "bubble" their way to the top and the larger values sink to the bottom.

The algorithm can be described as follows:

boolean changed = true;
do {
  changed = false;
  for (int j = 0; j < list.length - 1; j++)
    if (list[j] > list[j + 1]) {
      swap list[j] with list[j + 1];
      changed = true;
    }
} while (changed);

 

Clearly, the list is in increasing order when the loop terminates.
It is easy to show that the do loop executes at most list.length –1 times.

Use {6.0, 4.4, 1.9, 2.9, 3.4, 2.9, 3.5} to test the method.
*/
class P6Q17{
  public static void main(String[] args){
    double[] test={6.0, 4.4, 1.9, 2.9, 3.4, 2.9, 3.5};
    print(test);
    bubbleSort(test);
    print(test);
  }
  static void print(double[] array){
    for(int i=0;i<array.length;i++)
      System.out.printf("%-5.1f",array[i]);
    System.out.println();
  }
  static void bubbleSort(double[] array){
  boolean judge=true;
  do{
    judge=false;
    for(int i=0;i<array.length-1;i++)
      if(array[i]>array[i+1]){
      array[i]=array[i]+array[i+1];
      array[i+1]=array[i]-array[i+1];
      array[i]=array[i]-array[i+1];
      judge=true;
    }
  }while(judge);
  }
}

 


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

Powered by X-Space 1.2 © 2001-2006 Comsenz Technology Ltd