一些排序算法

最近闲来无事就顺手写写 呵呵 权当练手了

/**
 * 一些排序的算法
 * @author chengxvdong
 */
public class PaiXv {

 /**
  * @param args
  */
 public static void main(String[] args) {
  PaiXv paiXv = new PaiXv();
  int[] a = {3,6,9,2,7,8,1};
  
  paiXv.maoPao(a);
  paiXv.display(a);
  paiXv.xvanZe(a);
  paiXv.display(a);
  paiXv.chaRu(a);
  paiXv.display(a);
  paiXv.reversal(a);
  paiXv.display(a);
 }
 
 /**
  * 将数组倒过来(采用的冒泡排序的思想)
  * @param shuZu
  */
 public void reversal(int[] shuZu){
  int length = shuZu.length;
  for (int i = 1; i < length; i++) {
   for (int j = 0; j < length - i; j++) {
    swap(shuZu, j, j + 1);
   }
  }
 }
 
 /**
  * 插入排序
  * @param shuZu
  */
 public void chaRu(int[] shuZu){
      int length = shuZu.length;
      for (int i = 1; i < length; i++) {
      int index = i;
      int temp = shuZu[i];
   while (index > 0 && shuZu[index - 1] > temp) {
    shuZu[index] = shuZu[index - 1];
    index--;
   }
   shuZu[index] = temp;
  }
    
 }
 
 /**
  * 选择排序
  * @param shuZu
  */
 public void xvanZe(int[] shuZu){
  int length = shuZu.length;
  for (int i = 0; i < length; i++) {
   int min = i;
   for (int j = i + 1; j < length; j++) {
    if (shuZu[min] > shuZu[j]) {
     min = j;
    }
   }
   swap(shuZu, min, i);
  }
 }
 
 
 /**
  * 冒泡排序
  * @param shuZu
  */
 public void maoPao(int[] shuZu){
  int length = shuZu.length;
  for (int i = 1; i < length; i++) {
   for (int j = 0; j < length - i; j++) {
    if (shuZu[j] > shuZu[j+1]) {
     swap(shuZu, j, j + 1);
    }
   }
  }
 }
 
 /**
  * 传入数组和要交换的下标
  * @param shuZu
  * @param index1
  * @param index2
  */
 public void swap(int[] shuZu,int index1,int index2){
  int temp = shuZu[index1];
  shuZu[index1] = shuZu[index2];
  shuZu[index2] = temp;
 }
 
 /**
  * 迭代打印数组
  * @param shuZu
  */
 public void display(int[] shuZu){
  int length = shuZu.length;
  StringBuffer sbf = new StringBuffer();
  for (int i = 0; i < length; i++) {
   sbf.append(shuZu[i]).append(",");
  }
  System.out.println(sbf.substring(0, sbf.length() - 1));
 }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值