基本排序算法——冒泡排序java实现

时间:2021-12-10 23:42:47

冒泡排序是原理最简单的一种排序算法,具体思想就不多说了,代码如下:

eclipse4.3中编译通过

 package sort.basic;

 import java.util.Arrays;

 public class bubbleSort {

     private static int[] nums={34,78,90,45,3432,343,43,545,464,57,23,1323};

     public static int[] bubbleSortOnce(){
int[] num = nums; for(int i=0; i<num.length ;i++){
for(int j =1 ; j < num.length -i; j++){
if(num[j] < num[j-1] ){
int tmp = num[j];
num[j] = num[j-1];
num[j-1] = tmp;
}
}
}
return num;
} public static int[] bubbleSortTwice(){
int[] num = nums;
boolean exchanged = true;
for(int i=0; i<num.length && exchanged ;i++){
for(int j =1 ; j < num.length -i ; j++){
exchanged = false;
if(num[j] < num[j-1] ){
int tmp = num[j];
num[j] = num[j-1];
num[j-1] = tmp;
exchanged = true;
}
}
}
return num;
} public static void main(String[] args){
println(Arrays.toString(bubbleSortOnce()));
println(Arrays.toString(bubbleSortTwice()));
} private static void println(String str){
System.out.println(str);
}
}

具体运行吧,