我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*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);
}
}
导入论坛查看(33)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing