(7) Sorting algorithm: merge sort

One, the steps of merging and sorting

      1. Split a set of data to be sorted into two arrays with the same number of elements, and continue to split each array until the number of elements in each array after splitting is 1.

      2. Combine two adjacent subgroups into an ordered group

      3. Repeat the steps until there is only one group in the end

      The steps are as follows:

      

2. Code and running results:

 

#include <iostream>

using namespace std;


template <class T>
class Merge
{
public :
	Merge(T arry[], int num)
	{
		pAssist = new T[num];

		sort(arry,num);
	}

	~Merge()
	{
		delete[] pAssist;
	}


private:

	void sort(T arry[], int size);

	void sort(T arry[], int lo, int h);

	void combine(T arry[],int lo,int mid,int h); //合并

	T* pAssist;

};

template <class T>
void Merge<T>::sort(T  arry[], int lo,int h)
{
	if (lo >= h) //递归终止的条件
	{
		return;
	}

	//将lo到h之间的数据分成两组
	int mid = lo + (h - lo) / 2;

	//对每组数据进行排序
	sort(arry,lo,mid);
	sort(arry,mid + 1,h);

	//最终将排序完的两组数据合并
	combine(arry,lo,mid,h);
}

template <class T>
void Merge<T>::sort(T arry[],int size)
{
	int lo = 0;
	int hi = size - 1;

	sort(arry,lo,hi);
}


template <class T>
void Merge<T>::combine(T arry[], int lo, int mid, int h)
{
	int i = lo;
	int index1 = lo;
	int index2 = mid + 1;


	//将两个数组中的数据合并到pAssist
	while ((index1 <= mid) && (index2 <= h))
	{
		if (arry[index1] < arry[index2])
			pAssist[i++] = arry[index1 ++];
		else
			pAssist[i++] = arry[index2++];
	}
	
	//把剩余的元素放到pAssist
	while(index1 <= mid)
		pAssist[i++] = arry[index1++];

	while (index2 <= h)
		pAssist[i++] = arry[index2++];

	//将pAssist中的元素放回到arry中
	for (int lop = lo; lop <= h; lop++)
		arry[lop] = pAssist[lop];
}


int main()
{
	int arr[] = { 3,2,1 ,4,6,1};

	Merge<int> merge(arr,sizeof(arr)/sizeof(arr[0]));

	for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
		cout << arr[i] << " ";

	cout << endl;

  

	return 0;
}


operation result:

 

 

Third, the time complexity of merge sort

  Taking 8 numbers as an example, the steps for splitting are as follows:

   A total of split $\log_2^8$= 3 times, so the tree has a total of 3 layers, and there are a total of 2^k arrays from the top to the kth level. The length of each array is 2^(3-k), and each group of data requires at most 2^ (3-k) comparisons,

Therefore, the number of comparisons for each layer = 2^k * 2^(3-k) = 2^3, and the total of 3 layers is 3*2^3 times

  Assuming there are a total of N numbers, then the number of merging and splitting is $\log_2^N$times. The tree has a total of $\log_2^N$layers. $\log_2^N$Replace the number of layers of 3*2^3. The final time complexity is:

$\log_2^N$*2^ $\log_2^N$= $\log_2^N$*N, according to the Big O rule, ignoring the base, the final time complexity is O(N $\log_2^N$)

 

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/109463476