📅  最后修改于: 2020-10-15 03:09:03             🧑  作者: Mango
合并排序是遵循分而治之的算法。考虑一个n个元素的数组A。该算法分3个步骤处理元素。
合并排序的主要思想是,简短列表的排序时间更少。
Complexity | Best case | Average Case | Worst Case |
---|---|---|---|
Time Complexity | O(n log n) | O(n log n) | O(n log n) |
Space Complexity | O(n) |
考虑以下由7个元素组成的数组。使用合并排序对数组进行排序。
A = {10, 5, 2, 23, 45, 21, 7}
MERGE_SORT(ARR,BEG,END)
#include
void mergeSort(int[],int,int);
void merge(int[],int,int,int);
void main ()
{
int a[10]= {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
int i;
mergeSort(a,0,9);
printf("printing the sorted elements");
for(i=0;i<10;i++)
{
printf("\n%d\n",a[i]);
}
}
void mergeSort(int a[], int beg, int end)
{
int mid;
if(begmid)
{
while(j<=end)
{
temp[index] = a[j];
index++;
j++;
}
}
else
{
while(i<=mid)
{
temp[index] = a[i];
index++;
i++;
}
}
k = beg;
while(k
输出:
printing the sorted elements
7
9
10
12
23
23
34
44
78
101
public class MyMergeSort
{
void merge(int arr[], int beg, int mid, int end)
{
int l = mid - beg + 1;
int r = end - mid;
intLeftArray[] = new int [l];
intRightArray[] = new int [r];
for (int i=0; i
输出:
Sorted array
23
23
23
34
45
65
67
89
90
101
using System;
public class MyMergeSort
{
void merge(int[] arr, int beg, int mid, int end)
{
int l = mid - beg + 1;
int r = end - mid;
int i,j;
int[] LeftArray = new int [l];
int[] RightArray = new int [r];
for (i=0; i
输出:
Sorted array
23
23
23
34
45
65
67
89
90
101