我理解的归并排序--------归并,即小块区域的排序,然后依次将小块组合成大块。
排序的原则是比较,只是比较的方式不同罢了,归并排序方式如下:
(1)选取一个中间位置mid = low + (high -low)/2;
(2) 然后分别从数组第一个元素arr[low](标注为fisrt)和中间位置后第一个元素arr[mid+1](标注为last)进行比较;
(3)申请临时备用temp[],用于存储low-high范围的数据;
(3)依次对数组arr中范围为low-high进行排序,比较temp[fisrt] 与 temp[last] 将较小的值赋值给arr当前值arr[k],并对较小的值的位置向前移动一个;
(4)最后,当fisrt已经超过mid的范围,则将临时数组temp在last之后的值继续赋值给arr[k];若last超过high的范围,则将临时数组temp在first之后的值继续赋值给arr[k]。
代码如下:
#include <vector>
#include <stdio.h>
void merge(std::vector<int>& input, int low, int mid, int high) {
if ( input.size() == 0 || low >= high || mid > high || low > mid) {
return ;
}
std::vector<int> temp_input(input);
//for (int i = low; i <= high; i++) {
// temp_input[i] = input[i];
//}
int first = low;
int last = mid+1;
for (int j = low; j <= high; j++) {
if (first > mid) {
input[j] = temp_input[last++];
}
else if (last > high) {
input[j] = temp_input[first++];
}
else {
input[j] = (temp_input[first] < temp_input[last]) ? temp_input[first++] : temp_input[last++];
}
}
}
void sort(std::vector<int>& input, int low, int high) {
if (input.size() == 0 || low >= high) {
return ;
}
int mid = low + (high - low) / 2;
sort(input, low, mid);
sort(input, mid + 1, high);
merge(input, low, mid, high);
}
int main() {
std::vector<int> input = {1,4,5,3,9,0};
int size = input.size();
sort(input, 0, size-1);
for (int i = 0; i < input.size(); i++) {
printf("value:%d\n", input[i]);
}
return 0;
}
结果: