日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

归并排序(C++版)

發布時間:2024/4/18 c/c++ 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 归并排序(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++版)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。