归并排序(Merge sorting)(C++)

一. 归并排序(Merge sorting)

归并排序(Merge sorting 是一种将数据分而治之(divide and conquer)的算法,其实现过程如下:

  • 将数据分为两部分(Divides the list into halves);
  • 每一半各自进行排序(Sort each halve separately);
  • 将排序结果汇总(Then merge the sorted halves into one sorted array)。

在这里插入图片描述

最差的情况如下图所示:

在这里插入图片描述

由图分析可知归并排序是一种稳定的排序算法,在最糟糕情况下的时间复杂度为O(n*log2(n)),平均时间复杂度为O(n*log2(n))

二. C++ 代码

#include <iostream>

using namespace std;

void merge(int arr[], int first, int mid, int last, int arr_size, int order)
{
    
    
	int tempArray[arr_size];
	int first1 = first;
	int last1 = mid;
	int first2 = mid + 1;
	int last2 = last;
	int index = first1;
	if(order == 1)
	{
    
    
		for(; (first1 <= last1) && (first2 <= last2); ++ index)
		{
    
    
			if(arr[first1] < arr[first2])
			{
    
    
				tempArray[index] = arr[first1];
				++first1;
			}
			else
			{
    
    
				tempArray[index] = arr[first2];
				++first2;
			}
		}
		for(; first1 <= last1; ++first1, ++index)
			tempArray[index] = arr[first1];
		for(; first2 <= last2; ++first2, ++index)
			tempArray[index] = arr[first2];
		for(index = first; index <= last; ++index)
			arr[index] = tempArray[index];
	}
	else
	{
    
    
		for(; (first1 <= last1) && (first2 <= last2); ++ index)
		{
    
    
			if(arr[first1] > arr[first2])
			{
    
    
				tempArray[index] = arr[first1];
				++first1;
			}
			else
			{
    
    
				tempArray[index] = arr[first2];
				++first2;
			}
		}
		for(; first1 <= last1; ++first1, ++index)
			tempArray[index] = arr[first1];
		for(; first2 <= last2; ++first2, ++index)
			tempArray[index] = arr[first2];
		for(index = first; index <= last; ++index)
			arr[index] = tempArray[index];
	}
}

void MergeSort(int arr[], int first, int last, int arr_size, int order)
{
    
    
	cout << "Split: ";
	for(int k = first; k<= last; k++)
		cout << arr[k] << " ";
	cout << endl;
	if(first < last)
	{
    
    
		int mid = (first + last) / 2;
		MergeSort(arr, first, mid, arr_size, order);
		MergeSort(arr, mid+1, last, arr_size, order);
		merge(arr, first, mid, last, arr_size, order);
	}
	cout << "Merge: ";
	for(int k = first; k <= last; k++)
		cout << arr[k] << " ";
	cout << endl;
} 

int main()
{
    
    
	int arr_size, order;
	int *arr;

	cout << "Enter the size of an integer array: ";
	cin >> arr_size;
	
	arr = new int[arr_size];
	for(int i = 0; i < arr_size; i++)
	{
    
    
		cout << "Enter an integer to be stored at position " << i << " : ";
		cin >> arr[i];
	}
	cout << "Choose the sorting order:\n 1 - Ascending\n 2 - Descending\n ";
	cin >> order;
	
	int first = 0;
	int last = arr_size - 1;
	
	MergeSort(arr, first, last, arr_size, order);
	
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/weixin_43361652/article/details/113392143
今日推荐