☆堆排序:效率高,时间复杂度O(N*log2N),空间复杂度O(1),稳定性:不稳定。
//堆排序
//作用:将下标为start-end之间的最大值放在start下标位置
public static void adjust(int[] array,int start,int end){
int tmp=array[start];
for(int i=2*start+1;i<=end;i=2*i+1){
//找到左右孩子中最大值的下标
if((i<end)&&array[i]<array[i+1]){
i++;
}
if(array[i]>tmp){
array[start]=array[i];
start=i;
}else if(array[i]<tmp){
break;
}
}
array[start]=tmp;
}
public static void heapSort(int[] array){
for(int i=(array.length-1-1)/2;i>=0;i--){
//第一次调整将0号下标放成最大值
adjust(array,i,array.length-1);
}
for(int j=0;j<array.length-1;j++){
//将已调整好的值放到下标为array.length-1-j中
int temp=array[array.length-1-j];
array[array.length-1-j]=array[0];
array[0]=temp;
//再次调整(除去已经有序的元素)
adjust(array,0,array.length-1-j-1);
}
}
☆快速排序的时间复杂度O(N*logN),空间复杂度(logN),不稳定
快速排序的基本思想:任取待排序元素序列中的某元素作为基准值,按照该排序码将待排序集合分割成两子序列,左子序列中所有元素均小于基准值,右子序列中所有元素均大于基准值,然后最左右子序列重复该过程,直到所有元素都排列在相应位置上为止。
public static int partition(int[] array,int low,int high){
int temp=array[low];
while (low<high){
while ((low<high)&&array[high]>=temp){
high--;
}
if(low>=high){
break;
}else {
array[low]=array[high];
}
while ((low<high)&&array[low]<=temp){
low++;
}
if(low>=high){
break;
}else {
array[high]=array[low];
}
}
array[high]=temp;
return high;
}
public static void quickSort(int[] array,int low,int high){
if(low>=high){
return;
}
int mid=partition(array,low,high);
quickSort(array,low,mid-1);
quickSort(array,mid+1,high);
}
快排(非递归)
//快速排序(非递归)
public static int partion(int[] array,int low,int high){
int tmp=array[low];
while (low<high){
while ((low<high)&&array[high]>=tmp){
high--;
}
if(low>=high){
break;
}else {
array[low]=array[high];
}
while ((low<high)&&array[low]<=tmp){
low++;
}
if(low>=high){
break;
}else {
array[high]=array[low];
}
}
array[low]=tmp;
return low;
}
public static void quickSort(int[] array){
int[] stack=new int[array.length*2];
int top=0;
int low=0;
int high=array.length-1;
int par=partion(array,low,high);
if(par>low+1){
stack[top++]=low;
stack[top++]=par-1;
}
if(par<high-1){
stack[top++]=par+1;
stack[top++]=high;
}
while (top>0){
high=stack[--top];
low=stack[--top];
par=partion(array,low,high);
if(par>low+1){
stack[top++]=low;
stack[top++]=par-1;
}
if(par<high-1){
stack[top++]=par+1;
stack[top++]=high;
}
}
}
☆归并排序:将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有
序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
时间复杂度:O(N*logN) 空间复杂度:O(N) 稳定性:稳定。
public static void merage(int[] array,int start,int mid ,int end){
int[] tmpArray=new int[array.length];
int tmpIndex=start;
int start2=mid+1;
while(start<=mid&&start2<=end){
if(array[start]>array[start2]){
tmpArray[tmpIndex]=array[start2];
start2++;
tmpIndex++;
}else if(array[start]<=array[start2]){
tmpArray[tmpIndex]=array[start];
start++;
tmpIndex++;
}
}
while (start<=mid){
tmpArray[tmpIndex]=array[start];
start++;
tmpIndex++;
}
while (start2<=end){
tmpArray[tmpIndex]=array[start2];
start2++;
tmpIndex++;
}
}
public static void merageSort(int[]array,int start,int end){
if(start>=end){
return;
}
int mid=(start+end)/2;
merageSort(array,start,mid);
}
非比较排序:计数排序