1.希尔排序
插入排序的改进算法,不稳定的排序算法,空间复杂度为O(1)
public static void shellSort(int a[]){
int k=a.length;
int temp;
while (k>1) {
k=(k+1)/2;
for (int i = 0; i < a.length-k; i++) {
if (a[i]>a[i+k]) {
temp=a[i];
a[i]=a[i+k];
a[i+k]=temp;
}
}
}
}
2.快速排序
冒泡排序的改进算法,不稳定的排序算法
空间复杂度在O(log2n)和O(n)之间
时间复杂度在O(n)和O(n2)之间,平均时间复杂度为O(nlog2n),而当数组初始有序的条件下,快速排序会退化为冒泡排序
//一趟快速排序算法
public static int partition(int i,int j){
int temp=a[i];
while (j>i) {
while (temp<=a[j]&&j>i) {
j--;
}
if (j>i) {
a[i]=a[j];
i++;
}
while (temp>=a[i]&&j>i) {
//写temp>=a[i],将i误写成了j浪费了大量时间排错
i++;
}
if (j>i) {
a[j]=a[i];
j--;
}
}
a[i]=temp;
return i;
}
//static int count=0;
//递归调用partition()函数,进行多趟排序直至整个数组有序
public static void qSort(int low,int high){
if (high>low) {
int i=partition(low, high);
qSort(low, i-1);
qSort(i+1, high);
//System.out.print(++count);
}
}
public static void quickSort(int []a){
qSort(0, a.length-1);
}
3.堆排序
树形排序的改进型排序算法,不稳定的排序算法
空间复杂度O(1)
时间复杂度O(nlog2n)
public static void shift(int low,int high){
int i=low;
int j=2*i+1;
int temp=a[i];
while (j<high) {
if (j<high-1&&a[j]>a[j+1]) {
j++;
}
if (a[i]>a[j]) {
a[i]=a[j];
i=j;
j=2*i+1;
}else {
j=high+1;
}
}
a[i]=temp;
}
public static void heapSort(){
int len=a.length;
int temp;
//初始化堆
for (int i=len/2-1;i>=0;i--) {
shift(i, len);
}
//将最小关键字值交换到后面,再调整堆
for (int i=len-1;i>0;i--) {
temp=a[0];
a[0]=a[i];
a[i]=temp;
shift(0, i);
}
}