/**
*des:冒泡排序算法的一般性策略:搜索整个值列,比较相邻元素,如果两者的相对次序不对,
*则交换它们,其结果是最大值“想水泡一样”移动到值列的最后一个位置上,
*这也是它在最终完成排序的值列中合适的位置。
*然后再次搜索值列,将第二大的值移动至倒数第二个位置上,重复该过程,直至将所有元素移动到正确的位置上。
*2014-4-9-zbl
**/
public class BubbleSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Comparable []a={4,9,23,1,45,27,5,2};
bubbleSort1(a);
Comparable []b={4,9,23,1,45,27,5,2};
bubbleSort2(b);
int []c={4,9,23,1,45,27,5,2};
bubbleSort3(c);
}
public static void bubbleSort3(int []data)
{
int temp;
for (int i = 0; i < data.length; i++) {
int flag = 0;
for (int j = 0; j < data.length-i-1; j++) {
if (data[j]<data[j+1]) {
temp=data[j];
data[j]=data[j+1];
data[j+1]=temp;
flag = 1;
}
}
if(flag==0)break;
System.out.print("第"+i+"遍:{");
for (int k = 0; k < data.length; k++) {
System.out.print(data[k]+",");
}
System.out.println("}");
}
}
public static void bubbleSort1(Comparable []data)
{
Comparable temp;
for (int position = data.length-1; position >=0; position--) {
int flag = 0;
for (int scan = 0; scan < position; scan++) {
if(data[scan].compareTo(data[scan+1])<0){
temp = data[scan];
data[scan] = data[scan+1];
data[scan+1] = temp;
flag = 1;
}
}
if (flag==0) {
break;
}
System.out.print("第"+position+"遍:{");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+",");
}
System.out.println("}");
}
}
public static void bubbleSort2(Comparable []data)
{
Comparable temp;
for (int position = 0; position < data.length-1; position++) {
int flag = 0;
for (int scan = 0; scan < data.length-1-position; scan++) {
if(data[scan].compareTo(data[scan+1])<0){
temp = data[scan];
data[scan] = data[scan+1];
data[scan+1] = temp;
flag = 1;
}
}
if (flag==0) {
break;
}
System.out.print("第"+position+"遍:{");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]+",");
}
System.out.println("}");
}
}
}
Java冒泡排序算法的几种实现
最新推荐文章于 2020-03-16 20:20:54 发布