merge sort
归并排序:归并排序(英语:Merge sort,或mergesort),是创建在归并操作上的一种有效的排序算法,效率为O(n log n)。1945年由约翰·冯·诺伊曼首次提出。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用,且各层分治递归可以同时进行。
该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。
归并排序是稳定排序,它也是一种十分高效的排序
void mergeSort ( int array[], int min, int max) { // prerequisite if (min < max) { // get the middle point int mid = ( int )floor((max + min) / 2) ; // apply merge sort to both parts of this mergeSort(array, min, mid) ; mergeSort(array, mid + 1, max) ; // and finally merge all that sorted stuff merge(array, min, max, mid) ; } } void merge ( int array[], int min, int max, int mid) { int firstIndex = min ; int secondIndex = mid + 1 ; int index = min ; int tempArray[max] ; // if there are still objects in both arrays while ((firstIndex <= mid) && (secondIndex <= max)) { if (array[firstIndex] < array[secondIndex]) { tempArray[index] = array[firstIndex] ; index ++ ; firstIndex ++ ; } else { tempArray[index] = array[secondIndex] ; index ++ ; secondIndex ++ ; } } // terminates the object of the lower array while (firstIndex <= mid) { tempArray[index] = array[firstIndex] ; index ++ ; firstIndex ++ ; } // terminates the object of the upper array while (secondIndex <= max) { tempArray[index] = array[secondIndex] ; index ++ ; secondIndex ++ ; } // transfer to the initial array for ( int i = min ; i < index ; i ++ ) array[i] = tempArray[i] ; }
总的平均时间复杂度为O(nlogn)。而且,归并排序的最好,最坏,平均时间复杂度均为O(nlogn)。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!