主要思想
该算法是采用分治法,把数组不断分割,直至成为单个元素,然后比较再合并(合并的过程就是两部分分别从头开始比较,取出最小或最大元素的放到新的区域内,继续取两部分中最大或最小的元素,直到这两部分合并完,最后所有的都合并完,最后形成完整的有序序列)
图片理解## 代码实现
void mergeSort(int left , int right){
if((right - left) <= 0){
return;
}else {
mergeSort(left , (right + left) / 2);
mergeSort((right + left) / 2 + 1, right);
merge(left , right);
}
}
void merge(int left , int right){
int midleft = (left + right)/2;
int midright = midleft + 1;
int *arrA = new int [right - left + 1];
int i = left , j = midright;
int k = 0;
while(i <= midleft && j <= right){
if(arr[i] < arr[j]){
arrA[k++] = arr[i++];
}else if(arr[i] >= arr[j]){
arrA[k++] = arr[j++];
}
}
if(i <= midleft){
while(i <= midleft){
arrA[k++] = arr[i++];
}
}else if(j <= right){
arrA[k++] = arr[j++];
}
for(int i = left , k = 0; i <= right;i++,k++){
arr[i] = arrA[k];
}
}
void Show(){
for(int i = 0;i<=6;i++){
cout<<arr[i]<<" ";
}
}
int main(){
mergeSort(0,7);
Show();
return 0;
}
结果:
|