歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 關於冒泡算法實現

關於冒泡算法實現

日期:2017/3/1 9:40:34   编辑:Linux編程

首先冒泡算法就是每次把最大的找出來,冒泡出去,但是有2種不同實現。

C# 冒泡算法 http://www.linuxidc.com/Linux/2012-06/63178.htm

第一:

public class Test12{

public static void main(String[] args){/*

int score[] = {67, 88, 45, 87, 29, 99, 109, 100};

for (int i = 0; i < score.length -1; i++){ //最多做n-1趟排序

for(int j = 0 ;j < score.length - i - 1; j++){ //對當前無序區間score[0......length-i-1]進行排序(j的范圍很關鍵,這個范圍是在逐步縮小的)

if(score[j] > score[j + 1]){ //把小的值交換到後面

int temp = score[j];

score[j] = score[j + 1];

score[j + 1] = temp;

}

}

System.out.print("第" + (i + 1) + "次排序結果:");

for(int a = 0; a < score.length; a++){

System.out.print(score[a] + "\t");

}

System.out.println("");

}

System.out.print("最終排序結果 :");

for(int a = 0; a < score.length; a++){

System.out.print(score[a] + "\t");

}

*/

int[] score = {67, 88, 45, 87, 29, 99, 109, 100};

bubblesort(score);

}


第二種:

//===============冒泡排序---之最=====================================================

public static void bubblesort(int[] arry){

for(int i = 0;i < arry.length-1;i++){

for(int j = arry.length-1;j > i;j--){

if(arry[j]>arry[j-1]){

int temp = arry[j];

arry[j] = arry[j-1];

arry[j-1] = temp;

}

}

System.out.print("第"+(i+1)+"次排序:");

for (int i1 : arry) {

System.out.print(i1 +" ");

}

System.out.println();

}

}

Copyright © Linux教程網 All Rights Reserved