常用排序算法java实现

本文详细介绍了五种经典的排序算法:冒泡排序、插入排序、选择排序、快速排序及Shell排序。每种算法均提供了具体的实现代码,并对其时间复杂度、空间复杂度进行了分析。通过对这些算法的理解,读者可以更好地掌握排序算法的基本原理及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /**
  * 冒泡排序(平均时间复杂度o(n*n),最好o(n),最坏o(n*n),空间复杂度o(1))
  */
 public void bubbleSort(int [] a){
  
  for(int i = 0;i<a.length;i++){
   for(int j = 0;j<a.length-1-i;j++){
    if(a[j]>a[j+1]){
     int x = a[j];
     a[j] = a[j+1];
     a[j+1] = x;
    }
   }
  }
  show(a);  
 }
 
 /**
  * 插入排序(平均时间复杂度o(n*n),最好o(n),最坏o(n*n),空间复杂度o(1))
  */
 public void InsertSort(int [] a){
  for(int i = 1;i<a.length;i++){
   if(a[i-1]>a[i]){
    int x = a[i];
    int j = i-1;
    while(a[j]>x){
     a[j+1] = a[j];
     j--;
    }
    a[j+1] = x;
   }
  }
  show(a);
 }
 /**
  * 选择排序(平均时间复杂度o(n*n),最好o(n*n),最坏o(n*n),空间复杂度o(1))
  */
 public void SelectSort(int [] a){
  for(int i = 0;i<a.length;i++){
   int key = getMinKey(a,i);
   //System.out.print("-"+a[key]+"-");
   if(key!=i){
    int x = a[key];
    a[key] = a[i];
    a[i] = x;
   }
  }
  show(a);
  
 }
 public int getMinKey(int [] a,int a1){
  int min = a1;
  for(int i = a1+1;i<a.length;i++){
   if(a[min]>=a[i]){
    min = i;
   }
  }
  return min;
 }
 /**
  * 快速排序
  * 将比指定数晓得都放在前面,比指定数大的都放在该数后面,然后对前后重复以上步骤
  * (平均时间复杂度o(nlog2n),最好o(nlog2n),最坏o(n*n),空间复杂度o(nlog2n))
  */
 public void quickSort(int [] a,int b,int c){
  if(b<c)
  {
  int now = qs(a,b,c);
  quickSort(a,b,now-1);
  quickSort(a,now+1,c);
  }
 }
 private int qs(int [] a,int low,int high){
  int now = a[low];
  while(low<high){
   while(low<high&&a[high]>=now) --high;
   int x = a[low];
   a[low] = a[high];
   a[high] = x;
   while(low<high&&a[low]<=now) ++low;
   x = a[low];
   a[low] = a[high];
   a[high] = x;
  }
  
  return low;
 }
 /**
  * shell排序(平均时间复杂度o(n1.3),最好o(n),最坏o(n*n),空间复杂度o(1))
  *
  */
 public void shellSort(int [] a){
  int d = a.length;
  while(d>0){
   d = d/2;
   for(int x = 0;x<d;x++){
    for(int i = x+d;i<a.length;i=i+d){
     if(a[i-d]>a[i]){
      int z = a[i];
      int j = i-d;
      while(j>0&&a[j]>z){
       a[j+d] = a[j];
       j=j-d;
      }
      a[j+d] = z;
     }
    }
   }
  }
  show(a);
 }
 /**
  * 归并排序,将数组分成n/2个两个长度的数组,对其进行比较,再合并,进行排序。
  * (平均时间复杂度o(nlog2n),最好o(nlog2n),最坏o(nlog2n),空间复杂度o(1))
  */
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值