归并排序(C++版)
生活随笔
收集整理的這篇文章主要介紹了
归并排序(C++版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//歸并排序->先使子序列有序,再使子序列段間有序
//時間復雜度都是nlogn 空間復雜度是O(n)#include <iostream>
#include <vector>
using namespace std;void print(vector<int>& nums){for(auto a: nums){cout<<a<<" ";}cout<<endl;
}//nums:待排序數組,temp:用于排序的臨時數組,begin:排序區間的首元素位置,end:排序區間尾元素位置
void mergeSortCore(vector<int>& nums,vector<int>& temp,int begin,int end){if(begin>=end) return;int mid=begin+(end-begin)/2;//計算排序區間中間位置int start1=begin,end1=mid;//左區間int start2=mid+1,end2=end;//右區間mergeSortCore(nums,temp,start1,end1);//對左區間排序mergeSortCore(nums,temp,start2,end2);//對右區間排序int index=begin;//temp數組下標位置//把左右已經排序好的子數組合并while(start1<=end1&&start2<=end2){temp[index++]=nums[start1]>nums[start2]? nums[start2++]:nums[start1++];}//右邊子數組合并完,追加合并左數組while(start1<=end1){temp[index++]=nums[start1++];}//左邊子數組合并完,追加合并右數組while(start2<=end2){temp[index++]=nums[start2++];}//將臨時數組中的值復制到原數組*****for(index=begin;index<=end;index++){nums[index]=temp[index];}}
void mergeSort(vector<int>&nums){vector<int> temp(nums);mergeSortCore(nums,temp,0,nums.size()-1);///一定注意減一,因為是左閉右閉區間
}int main(){vector<int> nums{1,24,67,23,4,78,90,456};mergeSort(nums);print(nums);return 0;
}
總結
以上是生活随笔為你收集整理的归并排序(C++版)的全部內容,希望文章能夠幫你解決所遇到的問題。