基本排序算法——冒泡排序java实现
冒泡排序是原理最简单的一种排序算法,具体思想就不多说了,代码如下:
eclipse4.3中编译通过
1 package sort.basic; 2 3 import java.util.Arrays; 4 5 public class bubbleSort { 6 7 private static int[] nums={34,78,90,45,3432,343,43,545,464,57,23,1323}; 8 9 public static int[] bubbleSortOnce(){ 10 int[] num = nums; 11 12 for(int i=0; i<num.length ;i++){ 13 for(int j =1 ; j < num.length -i; j++){ 14 if(num[j] < num[j-1] ){ 15 int tmp = num[j]; 16 num[j] = num[j-1]; 17 num[j-1] = tmp; 18 } 19 } 20 } 21 return num; 22 } 23 24 public static int[] bubbleSortTwice(){ 25 int[] num = nums; 26 boolean exchanged = true; 27 for(int i=0; i<num.length && exchanged ;i++){ 28 for(int j =1 ; j < num.length -i ; j++){ 29 exchanged = false; 30 if(num[j] < num[j-1] ){ 31 int tmp = num[j]; 32 num[j] = num[j-1]; 33 num[j-1] = tmp; 34 exchanged = true; 35 } 36 } 37 } 38 return num; 39 } 40 41 public static void main(String[] args){ 42 println(Arrays.toString(bubbleSortOnce())); 43 println(Arrays.toString(bubbleSortTwice())); 44 } 45 46 private static void println(String str){ 47 System.out.println(str); 48 } 49 }
具体运行吧,
雨,静静的飘扬;
心,慢慢的行走;
程序人生,人生迈进。