当前位置:首页 > 编程语言 > 正文

java常见排序算法

11-18 编程语言

标签:oid   细节   nbsp   amp   选择   插入   nlogn   nlog   选择排序   

今天去面试的时候又考了排序算法,排序这个东西,你以为你懂了,但是真正去写的时候才会发现好多细节自己都模棱两可,我写着写着就全都乱了,回来之后赶紧重新写一遍。

(1)冒泡排序

public void bubbleSort(int a[]){
  int temp=0;
  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]){
        temp=a[j];
        a[j]=a[j 1];
        a[j 1]=temp;
       }
    }
  }
}
时间复杂度:O(N^2)

 

(2)快速排序

public void quickSort(int left,int right,int a[]){
    int l=left;  
    int r=right;
    int pivot=a[(left right)/2];
    int temp=0;
    while(l<r){
         while(a[l]<pivot)  l  ;
         while(a[r]>pivot   r--;
         if(l>r)  break;
         temp=a[l];
         a[l]=a[r];
         a[r]=temp;
         if(a[l]==pivot) --r;
         if(a[r]==pivot    l;
      }
    if(l==r){
    l  ;
    r--;
    }
    if(left<r)  sort(left,r,a);
    if(l<right)  sort(l,right,a);
}
//时间复杂度:O(NlogN)~O(N^2)

 

 

(3)插入排序

public insertSort(int a[]){
 for(int i=1;i<a.length;i  ){
     insertVal=a[i];
     index=i-1;
     while(index>=0&&insertVal<a[j]){
        a[j 1]=a[j];
        index--;
     }
   a[index 1]==insertVal;
  }
}
时间复杂度:O(N^2)

 

(4)选择排序

public void selectSort(int a[]){
   int temp=0;
   for(int i=0;i<a.length-1;i =){
      int min=a[i];
      int minIndex=i;
      for(int j=i 1;j<a.length;j  ){
         if(min>a[j]){
           min=a[j];
           minIndex=j;
         }
       }
      temp=a[i];
      a[i]=a[minIndex];
      a[minIndex]=temp;
  }
}
//时间复杂度:O(N^2)
 

java常见排序算法

标签:oid   细节   nbsp   amp   选择   插入   nlogn   nlog   选择排序   

温馨提示: 本文由杰米博客推荐,转载请保留链接: https://www.jmwww.net/file/biancheng/12073.html