#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/**
* Email 956324914@qq.com
* Author xlf
*/
/**
* Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right].
*/
template<typename T>
static void merge_(T *array, int left, int mid, int right) {
/*We need a Temporary array to store the new sorted part*/
T tempArray[right-left+1];
int pos=0,lpos = left,rpos = mid + 1;
while(lpos <= mid && rpos <= right) {
if(array[lpos] < array[rpos]) {
tempArray[pos++] = array[lpos++];
}
else {
tempArray[pos++] = array[rpos++];
}
}
while(lpos <= mid) tempArray[pos++] = array[lpos++];
while(rpos <= right)tempArray[pos++] = array[rpos++];
int iter;
/* Copy back the sorted array to the original array */
for(iter = 0;iter < pos; iter++) {
array[iter+left] = tempArray[iter];
}
return;
}
/**
* sort an array from left->right
*/
template<typename T>
static void merge_sort(T *array, int left, int right) {
int mid = (left+right)/2;
/* We have to sort only when left<right because when left=right it is anyhow sorted*/
if(left<right) {
/* Sort the left part */
merge_sort(array,left,mid);
/* Sort the right part */
merge_sort(array,mid+1,right);
/* Merge the two sorted parts */
merge_(array,left,mid,right);
}
}
/**
* print all of the elements in `list` with size `n`
*/
template<typename T>
static void printlist(T & list,int count) {
int i;
for(i=0;i<count;i++)
printf("%d\t ",list[i]);
printf("\n");
}
int main()
{
const int MAX_ELEMENTS = 20;
int list[MAX_ELEMENTS];
int i = 0;
// generate random numbers and fill them to the list
for(i = 0; i < MAX_ELEMENTS; i++ ){
list[i] = rand()%100;
}
printf("The list before sorting is:\n");
printlist(list,MAX_ELEMENTS);
// sort the list using quicksort
merge_sort<int>(list,0,MAX_ELEMENTS-1);
// print the result
printf("The list after sorting using merge sort algorithm:\n");
printlist(list,MAX_ELEMENTS);
return 0;
}
归并排序算法的c++实现
最新推荐文章于 2023-03-29 11:49:17 发布