两种插入类排序:
直接插入排序:
public static void insertSort(int[] arr, int len){
for(int i=1; i<len; i++){
int temp = arr[i];
int j=i-1;
while(j>=0 && temp<arr[j]){
arr[j+1] = arr[j];
--j;
}
arr[j+1] = temp;
}
}
折半插入排序:
public static void binarySort(int[] arr,int len){
for(int i=1; i<len; i++){
int temp = arr[i];
int low = 0, high = i-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[i] > arr[mid]) low=mid+1;
else high = mid-1;
}
for(int j=i; j>low; --j){
arr[j] = arr[j-1];
}
arr[low] = temp;
}
}
两种交换类排序:
冒泡排序:
public static void bubbleSort(int[] arr,int len){
for(int i=len-1; i>=1; i--){
for(int j=1; j<=i; j++){
if(arr[j]<arr[j-1]){
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
}
快速排序:
public static void quickSort(int[] arr,int low, int high){
if(low<high){
int temp = arr[low];
int i = low,j = high;
while(i!=j){
while(i<j && arr[j]>=temp) --j;
if(i<j){
arr[i] = arr[j];
i++;
}
while(i<j && arr[i] < temp) ++i;
if(i<j) {
arr[j] = arr[i];
j--;
}
}
arr[i] = temp;
quickSort(arr,0,i-1);
quickSort(arr, i+1,high);
}
}
时间复杂度和空间复杂度:

方法调用:
public static void main(String[] args) {
int arr[] = {23,3,7,22,1,9,2};
//bubbleSort(arr,arr.length);
//quickSort(arr,0, arr.length-1);
//binarySort(arr,arr.length);
insertSort(arr,arr.length);
System.out.print("排序后为:");
for(int x : arr){
System.out.printf("%d,",x);
}
}