冒泡排序(Java)


算法核心
1 public void bubbleSort(){
2         for(int i=0;i<length;i++){              //一共进行几趟
3             for(int j=0;j<length-i-1;j++){      //每一趟中,最后i个已经为有序状态
4                 if(a[j]>a[j+1]){
5                     swap(j,j+1);
6                 }
7             }
8         }
9     }




完整算法

1
package bubbleSort; 2 3 public class Sort { 4 public static void main(String args[]){ 5 Array arr = new Array(10); 6 for(int i=0;i<10;i++){ 7 arr.insert(10-i); 8 } 9 arr.bubbleSort(); 10 arr.display(); 11 } 12 13 } 14 class Array{ 15 private int[]a; 16 private int length; 17 public Array(int max){ 18 a = new int[max]; 19 length=0; 20 } 21 public void insert(int value){ 22 a[length]=value; 23 length++; 24 } 25 public void display(){ 26 for(int i=0;i<a.length;i++){ 27 System.out.println("a["+i+"]="+a[i]); 28 } 29 } 30 public void bubbleSort(){ 31 for(int i=0;i<length;i++){ //一共进行几趟 32 for(int j=0;j<length-i-1;j++){ //每一趟中,最后i个已经为有序状态 33 if(a[j]>a[j+1]){ 34 swap(j,j+1); 35 } 36 } 37 } 38 } 39 public void swap(int indexa,int indexb){ 40 int temp = a[indexa]; 41 a[indexa]= a[indexb]; 42 a[indexb]=temp; 43 } 44 }

运行结果

原文地址:https://www.cnblogs.com/doudingbest/p/4477519.html