冒泡排序与交换排序源码 (附图,附注解)

来源:互联网 发布:吉林省事业编通用知 编辑:程序博客网 时间:2024/05/22 01:49

/**
 * 排序方式类
 * @author xiaoya
 *
 */
public class SortMethod {
 
 /**
  * 传递一个数组,返回冒牌排序之后的数组(按照传递的排序方式)
  * @param t 数组数据的单个类型
  * @param method 排序的方式:
  */
 public double[] bubbleSort(double[] a, String method){
  /*降序排序*/
  if(method.equals("desc")){
   /*排序过程*/
   for (int i = 0; i < a.length-1; i++) {
    for (int j = 0; j < a.length-1-i; j++) {
     if (a[j]<a[j+1]) {
      double temp = a[j];
      a[j] = a[j+1];
      a[j+1] = temp;
     }
    }
   }
   return a ;
   
  }else{
   return bubbleSort(a);
  }
  
 }
 /**
  * 默认按照升序排序
  * @param  数组
  */
 public double[] bubbleSort(double[] a){
  /*排序过程*/
  for (int i = 0; i < a.length-1; i++) {
   for (int j = 0; j < a.length-1-i; j++) {
    if (a[j]>a[j+1]) {
     double temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
    }
   }
  }
  return a ;
  
 }
 
 
 
 
 
 /**
  * 传递一个数组,返回交换排序之后的数组
  * desc:降序
  */
 public double[] convertSort(double[] num,String method ){
  if(method.equals("desc")){
   /*排序过程*/
   for (int i = 0; i < num.length; i++) {
    for (int j = i+1; j < num.length; j++) {
     if (num[i]<num[j]) {
      double temp = num[i];
      num[i]= num[j];
      num[j]= temp;
     }
    }
   }
   return num;
   
  }else{
   return convertSort(num);
  }
  
 }
 
 /**
  * 交换排序升序方式
  */
 public double[] convertSort(double[] num){
  for (int i = 0; i < num.length; i++) {
   for (int j = i+1; j < num.length; j++) {
    if (num[i]>num[j]) {
     double temp = num[i];
     num[i]= num[j];
     num[j]= temp;
    }
   }
  }
  return num;
 }

 

 

 


public class MainClass {
 public static void main(String[] args) {
  SortMethod sm = new SortMethod();
  
  double[] num = new double[100];
  //在num数组中添加数据
  for (int i = 0; i < num.length; i++) {
   num[i] =i;
  }
//  //测试冒泡排序
//  double[]  sortedNum =sm.bubbleSort(num,"desc");
//  for (double d : sortedNum) {
//   System.out.print(d+"\t");
//  }
//  
//  
//  System.out.println("\n\n---------------------------------------------------------------------------------\n\n");
//  //测试交换排序
//  sortedNum = sm.convertSort(num, "desc");
//  for (double d : sortedNum) {
//   System.out.print(d+"\t");
//  }
//  
    
 }
}

原创粉丝点击