转自 :
数组al[0,mid-1]和 al[mid,num-1],都分别有序。将其merge成有序数组al[0,num-1],要求空间复杂度O(1)
思路:由于要求空间复杂度为O(1),故不能使用归并排序
1、遍历0~mid -1,将其与a[mid]相比较,若 a[mid] < a[i]; 则将其交换,进入2
2、循环遍历a[mid~length],如果1中交换后a[mid] > a[mid+1] 则进行交换,进行插入排序,将a[mid]插入到正确位置
#include<iostream>
usingnamespace std;
voidInsertSort(int a[], int index, int length){
int temp;
for(int i = index; i<length; i++){
if(a[i] >= a[i+1]){
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
void sort(int a[], int mid, int length){
int temp;
for(int i=0; i<=mid-1; i++){
if(a[mid] < a[i]){
temp = a[i];
a[i] = a[mid];
a[mid] = temp;
InsertSort(a, mid, length - 1);
}
}
}
intmain()
{
int a[11] ={1, 4, 6, 7, 10, 2, 3, 8, 9, 15,16};
sort(a,5,11);
for(int i=0;i <11; i++)
cout << a[i]<<" ";
return 0;
}