java中的排序算法

public class SortDemo {
 private int [] ar;
 public static final int defaultSize = 10;
 public SortDemo(int length){
  ar = new int[length];
  init();
 }
 public SortDemo(){
  this(defaultSize);
 }
 public SortDemo(int [] a){
  ar = a;
 }
 //隨機給數組元素賦值
 public void init(){
  for(int i = 0;i<ar.length;i++){
   System.out.println((int)Math.random());
  }
 }
 //把數組輸出到屏幕
 public void showSort() {
  for(int i = 0;i<ar.length;i++){
   System.out.print(ar[i]+"  ");
  }
 }
 
 //1、冒泡排序
 public void bubbleSort() {
  int temp;
  for (int i=0;i<ar.length-1;i++) {
   
   for (int j =0;j<ar.length-i;j++) {
    
    if(ar[j]>ar[j+1]) {
     temp = ar[j];
     ar[j] = ar[j+1];
     ar[j+1] = temp;
    }
   }
  }
 }

 //2、選擇排序

public void selectSort() {

 int temp;

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

    for(int j = i+1;j<ar.length;j++) {

         if(ar[i]>ar[j]) {

             temp = ar[i];

             ar[j] = temp;

             ar[i] = ar[j];

         }

    }

  }

}
 public static void main(String [] args) {
  int [] ts = {21,32,43,45,52,56,67,24,57,85,3};
  SortDemo s1 = new SortDemo(ts);
  System.out.println("數組未排序前:");
  s1.showSort();
  System.out.println();
  s1.bubbleSort();
  System.out.println("數組排序後:");
  s1.showSort();
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章