首页 / 算法 / 算法学习之排序(6)--合并排序
算法学习之排序(6)--合并排序
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了算法学习之排序(6)--合并排序,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2779字,纯文字阅读大概需要4分钟。
内容图文
一.算法描述
二.时间复杂度
三.空间复杂度
四.C++实现
#include <iostream> #include "Sort.h" #include "randomarray.h" bool Merge(std::vector<int>::iterator Ite, int LeftIndex, int RightIndex) { if (LeftIndex >= RightIndex) { return false; } if (LeftIndex == (RightIndex - 1)) { return true; } int Mid = (LeftIndex + RightIndex) / 2; // copy the array std::vector<int> LeftArray; for (int Index = LeftIndex; Index < Mid; Index++) { int Tmp = *(Ite + Index); LeftArray.push_back(*(Ite + Index)); } std::vector<int> RightArray; for (int Index = Mid; Index < RightIndex; Index++) { int Tmp = *(Ite + Index); RightArray.push_back(*(Ite + Index)); } // merge the sub array for (int Index_left = 0, Index_right = 0, Index = LeftIndex; Index < RightIndex; Index++) { // Ended merge the left array if (Index_left >= LeftArray.size()) { int Tmp = RightArray[Index_right]; *(Ite + Index) = RightArray[Index_right++]; continue; } // Ended merge the right array if (Index_right >= RightArray.size()) { int Tmp = LeftArray[Index_left]; *(Ite + Index) = LeftArray[Index_left++]; continue; } // merge the two array if (RightArray[Index_right] > LeftArray[Index_left]) { int Tmp = LeftArray[Index_left]; *(Ite + Index) = LeftArray[Index_left++]; } else { int Tmp = RightArray[Index_right]; *(Ite + Index) = RightArray[Index_right++]; } } return true; } bool MergeSort(std::vector<int>::iterator Ite, int LeftIndex, int RightIndex) { // return false if the LeftIndex >= RightIndex if (LeftIndex >= RightIndex) { return false; } // return true when there are only one element in the array if (LeftIndex == (RightIndex - 1)) { return true; } // split the array to two sub array int Mid = (LeftIndex + RightIndex) / 2; MergeSort(Ite, LeftIndex, Mid); MergeSort(Ite, Mid, RightIndex); // Merge the sub array return Merge(Ite, LeftIndex, RightIndex); } bool MergeSort(std::vector<int>& Array) { int Size = Array.size(); if (Size == 0) { return false; } if (Size == 1) { return true; } return MergeSort(Array.begin(), 0, Size); }
五.参考文献
原文:http://blog.csdn.net/sheng_ai/article/details/44664619
内容总结
以上是互联网集市为您收集整理的算法学习之排序(6)--合并排序全部内容,希望文章能够帮你解决算法学习之排序(6)--合并排序所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。