ESP-IDF:归并排序测试
/归并排序测试/
void printarry18 (int arr[],int length) {
for(int i=0;i<length;i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
void merge(int arr[],int start, int end, int mid,int * temp) {
int length = 0;//记录temp数组的长度
int i_start = start;
int i_end = mid;
int j_start = mid+1;
int j_end = end;
while (i_start <= i_end && j_start <= j_end) {
if(arr[i_start]<arr[j_start]) {
temp[length] =arr[i_start];
length++;
i_start++;
} else {
temp[length] = arr[j_start];
length++;
j_start++;
}
}
//有一边还有一个元素没有拷贝到temp中,判断并拷贝进去
while(i_start<= i_end){
temp[length] = arr[i_start];
length++;
i_start++;
}
while(j_start<= j_end){
temp[length] = arr[j_start];
length++;
j_start++;
}
//把temp中的这段合并序列,拷贝回arr中,从i_start到j_end
for(int i = 0; i<length;i++) {
arr[start+i] = temp[i];
}
}
void mergeSort(int arr[],int start, int end, int * temp) {
//分组退出条件
if (start >= end){
return;
}
int mid = (end + start)/2;//分组
//否则递归进行分组到左右只有一个元素,左右都是有序的
mergeSort(arr,start,mid,temp); //左边递归分组
mergeSort(arr,mid+1,end,temp); //右边递归分组
merge(arr,start,end,mid,temp); //左右有序序列合并
}
void test18() {
cout<<“--------test 归并排序 --------”<<endl;
int arr[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0,9, 8, 7, 6, 5, 4, 3, 2, 1, 0,9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int temp[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int length = sizeof(arr)/sizeof(int);
printarry18(arr,length);
mergeSort(arr,0,length-1,temp);
printarry18(arr,length);
}
extern “C” void app_main(void)
{
test18();
}