java中的排序算法

来源:互联网 发布:扬州大学怎么样 知乎 编辑:程序博客网 时间:2024/05/18 17:04

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();
 }
}

原创粉丝点击