Merge sort in C + +


This example for you to share a C + + merge sort of specific code, for your reference, the specific content is as follows

1、 Idea: stable sorting

(1) Partition: the partition procedure is called until the subsequence is empty or there is only one element. Log2 (n) is required;

(2) Merge: merge two subsequences into one sequence from small to large

2、 Implementation procedure:

//Merge sort: (two way merge)
//(1) Recursively decompose arrays;
//(2) merging ordered sequences
#include <iostream>
using namespace std;
//Merging two ordered sequences
template <typename T>
void Merge(T arr[], int start, int mid, int end) {
  int i, j, k, n1, n2;
  n1 = mid - start + 1;
  n2 = end - mid;
  T *L = new T[n1], *R = new T[n2];
  For (I = 0; I < N1; I + +) // assign the left part of arr to L
    L[i] = arr[start+i];
  For (J = 0; J < N2; j + +) // assign the right part of arr to R
    R[j] = arr[mid+j+1];
  i = 0;
  j = 0;
  k= start;
  While (I < N1 & & J < N2) {// merge
    if(L[i] <= R[j]) {
      arr[k] = L[i];
    } else {
      arr[k] = R[j];
  While (I < N1) {// the left part is not finished
    arr[k] = L[i];
  While (J < N2) {// the right part is not finished
    arr[k] = R[j];
  delete []L;
  delete []R;
//Merge sort
template <typename T>
void MergeSort(T arr[], int start, int end) {
  int mid;
  if(start >= end)
  mid = (start + end) / 2;
  MergeSort(arr, start, mid);
  MergeSort(arr, mid+1, end);
  Merge(arr, start, mid, end);
//Output array
template <typename T>
void Print(T arr[], int n) {
  int i;
  for(i = 0; i < n; i++)
    cout << arr[i] << " ";
  cout << endl;
int main(int argc, const char * argv[]) {
  int n, i, arr[50];
  Cout < "please enter the number of numbers to sort":;
  cin >> n;
  Srand ((int) time (null)); // set the time to a random point
  For (I = 0; I < n; I + +) // generate N random numbers
    arr[i] = rand() % 100;
  Cout < "before sorting":;
  Print(arr, n);
  Mergesort (arr, 0, n-1); // call merge sort
  Cout < "after sorting":;
  Print(arr, n);
  return 0;

Test results:

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Don’t be a tool man. Touching hands teaches you Jenkins!

Hello everyone, I’m a piece of cake, a piece of cake eager to be Cai Bucai in the Internet industry. Soft or hard, praise is soft, white whoring is just!Ghost ~ remember to give me a third company after watching it! This article mainly introducesJenkins If necessary, please refer to If it helps, don’t forgetgive […]