- 冒泡排序
- 属于交换排序
- 稳定排序
- 最佳情况:正序,只需n-1比较
- 最佳时间复杂度:O(n)
- 最差情况:逆序
- 最差时间复杂度:O(n^2)
- 平均时间复杂度:O(n^2)
- 空间复杂度:O(1)
Demo
void bubbleSort(int a[],int n){
int i,j,temp;
for( i = n; i > 1; i-- ){
for ( j = 0; j < i - 1; j++ ){
if( a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
- 快速排序
- 属于交换排序
- 不稳定排序
- 最佳情况:划分的平均
- 最佳时间复杂度O( n * lgn )
- 最差情况:划分的最不平均
- 最差时间复杂度:O(n^2)
- 平均时间复杂度:O(n * lgn)
- 空间复杂度:O(1)
Demo
public class Sort {
public static void quickSort(int[] a,int p,int r){
if( p < r){
int q = partition(a,p,r);
quickSort(a,p,q-1);
quickSort(a,q+1,r);
}
}
public static int partition(int[] a,int p,int r){
int x = a[r];
int i = p-1;
int temp = 0;
for(int j = p; j <= r-1; j++){
if( a[j] <= x){
i++;
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
temp = a[r];
a[r] = a[i+1];
a[i+1] = temp;
return i+1;
}
}