[go: up one dir, main page]

0% found this document useful (0 votes)
84 views1 page

#Include #Include Using Namespace Void Int Int Int Int Int Void Int Int Void Int Int Int Int Int Int

This C++ code implements a merge sort algorithm to sort an array of integers. It uses a recursive MergeSort function that divides the array in half, recursively sorts the left and right halves, and then merges the sorted halves back together into the original array. The Merge function takes two sorted arrays and merges them into a single sorted array.

Uploaded by

Pei Yang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views1 page

#Include #Include Using Namespace Void Int Int Int Int Int Void Int Int Void Int Int Int Int Int Int

This C++ code implements a merge sort algorithm to sort an array of integers. It uses a recursive MergeSort function that divides the array in half, recursively sorts the left and right halves, and then merges the sorted halves back together into the original array. The Merge function takes two sorted arrays and merges them into a single sorted array.

Uploaded by

Pei Yang
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

/* Merge sort in C++ */

#include <iostream>
#include <string>
using namespace std;
void Merge(int *A,int *L,int leftCount,int *R,int rightCount);
void MergeSort(int *A,int n);
void Merge(int *A,int *L,int leftCount,int *R,int rightCount) {
int i,j,k;
i = 0; j = 0; k =0;
while(i<leftCount && j< rightCount) {
if(L[i] < R[j]) A[k++] = L[i++];
else A[k++] = R[j++];
}
while(i < leftCount) A[k++] = L[i++];
while(j < rightCount) A[k++] = R[j++];
}
// Recursive function to sort an array of integers.
void MergeSort(int *A,int n) {
int mid,i, *L, *R;
if(n < 2) return;
mid = n/2;
// create left and right subarrays
L= new int[mid*sizeof(int)];
R= new int[(n-mid)*sizeof(int)];
for(i = 0;i<mid;i++) L[i] = A[i]; // creating left subarray
for(i = mid;i<n;i++) R[i-mid] = A[i]; // creating right subarray
MergeSort(L,mid); // sorting the left subarray
MergeSort(R,n-mid); // sorting the right subarray
Merge(A,L,mid,R,n-mid); // Merging L and R into A as sorted list.
delete[] L;
delete[] R;
}

You might also like