Merge Sort: segmentation fault c++ - c++

For some odd reason, I am getting a segmentation fault when I call the merge function. I am using g++ to compile and have tried passing in different data for the parameters, but I still get this issue.
#include <iostream>
using namespace std;
// Merges two sorted subarrays of A[].
// First sorted subarray is A[l..m].
// Second sorted subarray is A[m+1..r].
// You might want to call this function in function mergeSort().
void merge(int A[], int l, int m, int r) {
int i = 1; //Starting index for left sub array
int j = m + 1; //Starting index for right sub array
int k = 1; //starting index for temp
int *temp = new int[r];
while (i <= m && j <= r) {
if (A[i] <= A[j]) {
temp[k] = A[i]; //A[i] is actually smoler than A[j]
i++;
k++;
}
else {
if (A[i] <= A[j]) {
temp[k] = A[i]; //A[j] is actually smoler than A[i]
j++;
k++;
}
}
//Copy all elements from left sbuarray to temp
while(i<=m){
temp[k] = A[i];
i++;
k++;
}
//Copy all elements from right subarray to temp
while(j<=r){
temp[k] = A[j];
i++;
k++;
}
for(int z =0; z <r; z++){
A[z] = temp[z];
}
}
}
// using mergeSort to sort sub-array A[l..r]
// l is for left index and r is right index of the
// sub-array of A[] to be sorted
void mergeSort(int A[], int l, int r) {
if (l < r) {
int middle = l + (r - l) / 2;
mergeSort(A, l, middle);
mergeSort(A, middle + 1, r);
merge(A, l, middle, r);
}
}
int main() {
cout << "Please enter the length (number of elements) of the input array: ";
int n;
cin >> n;
if (n <= 0) {
cout << "Illegal input array length!" << endl;
return 0;
}
int *A = new int[n];
cout << "Please enter each element in the array" << endl;
cout << "(each element must be an integer within the range of int type)."
<< endl;
for (int i = 0; i < n; i++) {
cout << "A[" << i << "] = ";
cin >> A[i];
}
cout << "Given array A[] is: ";
for (int i = 0; i < n - 1; i++)
cout << A[i] << ",";
cout << A[n - 1] << endl;
mergeSort(A, 0, n - 1);
cout << "After mergeSort, sorted array A[] is: ";
for (int i = 0; i < n - 1; i++)
cout << A[i] << ",";
cout << A[n - 1] << endl;
delete[] A;
return 0;
}
The merge function is the problem of my program. I have tried debugging and whatnot but cannot determine the problem.

Try using the below code :-
#include<iostream>
using namespace std;
void merge(int arr[],int l,int m,int h)
{
int n1=m-l+1;
int n2=h-m;
int L[n1],M[n2];
for(int i=0;i<n1;i++)
L[i]=arr[l+i];
for(int i=0;i<n2;i++)
M[i]=arr[m+1+i];
int i=0,j=0,k=l;
while(i<n1&&j<n2)
{
if(L[i]<=M[j])
arr[k++]=L[i++];
else
arr[k++]=M[j++];
}
while(i<n1)
arr[k++]=L[i++];
while(j<n2)
arr[k++]=M[j++];
}
void mergesort(int arr[],int l,int h)
{
if(l>=h)
return;
int m=l+(h-l)/2;
mergesort(arr,l,m);
mergesort(arr,m+1,h);
merge(arr,l,m,h);
}
int main()
{
int n;
cout<<"Enter the no of element to be sorted:- ";
cin>>n;
int arr[1000000];
for(int i=0;i<n;i++)
arr[i]=rand();
mergesort(arr,0,n-1);
for(int i=0;i<n;i++)
cout<<arr[i]<<endl;
}
here is the output on online compiler:-

The problem is in this block of code.
while (j <= r) {
temp[k] = A[j];
i++; // Here it should be j++ instead of i++
k++;
}
You are incrementing i whereas you should increment j. This still produces the wrong output though.
Use debugger to find what's wrong with your code.

Related

Can't find the minimum in an array with respect to maximum from the same array

I wanted to write a program to take two arrays as input and convert the first array such that the difference of maximum value and minimum value from the first array gives the smallest possible number.
I tried to write a code to find a smaller number most closest to the maximum from the array in C++, but the function for finding the minimum works on Codelite, but not on other compilers;
Is there any fix to solve this, either to the code or the compiler?
Here is the code I tried:
#include <iostream>
using namespace std;
void swap(int A[], int B[], int n)
{
int x, y, temp;
for(x=0;x<n;++x)
{
for(y=0;y<n;++y)
{
if(A[x]>B[y])
{
temp = A[x];
A[x] = B[y];
B[y] = temp;
}
}
}
}
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
{
if (A[i] > A[j+1])
{
temp = A[i];
A[i] = A[j+1];
A[j+1] = temp;
}
}
}
}
int maxfind(int A[], int n)
{
int z, a;
a = A[0];
for(z=0;z<n;++z)
{
if(a<A[z])
{
a = A[z];
}
}
cout << "Max value in A is" << a << endl;
return a;
}
int minfind(int A[], int n, int amax, int amin)
{
int z, maxi;
maxi = amax;
for(z=0;z<n;++z)
{
if(maxi >= A[z])
{
amin = A[z];
}
else
{
maxi = maxi-1;
}
}
cout << "Mix value in A is" << amin << endl;
return amin;
}
int main() {
int z, t;
cout << "Enter number of test cases: ";
cin >> t;
int n, i, j, amax, amin;
for(z=0;z<t;++z)
{
cout << "Enter size of array" << endl;
cin >> n;
int A[n], B[n];
cout << "Enter Array A values:" << endl;
for(i=0;i<n;++i)
{
cin >> A[i];
}
cout << "Enter Array B values:" << endl;
for(j=0;j<n;++j)
{
cin >> B[j];
}
swap(A, B, n);
sortas(A, n);
cout << "Swapped and sorted array is: " << endl;
for(i=0;i<n;++i)
{
cout << A[i] << "\t" << B[i] << endl;
}
amax = 0;
amin = 0;
amax = maxfind(A, n);
amin = minfind(A, n, amax, amin);
}
return 0;
}
Here is the output to that code:
1 1 1 3 4 2
Max value in A is 1 Min value in A is 1
1 2 2
-1882830412 4 3 6 3
Max value in A is 2 Min value in A is -1882830412
The problem is with your bubble sort:
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++) // why not start at i + 1 ??
{
if (A[i] > A[j+1]) // j + 1 is out of bounds when j == n - 1
{
temp = A[i];
A[i] = A[j+1]; // <-- Some random value is written to A.
A[j+1] = temp; // <-- Overwriting some variable on the stack
// of main() (possibly B ?)
}
}
}
}
A correct bubble sort (this is not the pedantic bubble sort), this is probably the most used.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (A[i] > A[j])
std::swap(A[i], A[j]);
}
}
}
The actual bubble sort algorithn (the "pedantic" bubble sort), swaps only occur on neighboring values.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < (n - i) - 1; ++j)
{
if (A[j] > A[j + 1])
std::swap(A[j], A[j + 1]);
}
}
}
Use one or the other, for integers, the performance is identical.

why merge sorting is not working for 1,000,000 and 10,000,000 num? [duplicate]

This question already has answers here:
Segmentation fault on large array sizes
(7 answers)
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 4 months ago.
My merge sorting code in c++ , this code working for 100,000 int number but its not work for 1,000,000 and 10,000,000 int number and exit. Where is my code wrong?
I get the numbers randomly from the input. Are the random numbers I get correct?
void merge(int arr[], int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
int i, j, k;
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int n;
cout << "Enter Number: ";
cin >> n;
int array[n];
for(int i = 0; i<n; i++) {
array[i]=rand()%1000;
}
auto start2 = chrono::steady_clock::now();
mergeSort(array, 0, n - 1);
auto end2 = chrono::steady_clock::now();
auto diff2 = end2 - start2;
cout << "Time to sort for Merge: "<<chrono::duration <double, milli> (diff2).count() << " ms" << endl;
return 0;
}
I try with DevC++ but exit from codes. i want to using this get random code for another sorting.Is it correct to get input in this way?

Counting number of copying and comparisons in heapsort and insertation sort

I want to count how many times does algorithm makes comparisons and how many times algorithm makes copying.
#include <stdio.h>
#include <random>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <time.h>
void generuoti(int _N, const char *_file);
void nuskaityti(const char *_file);
int ps = 0;
int ks = 0;
void heapify(double arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
ps += 1;
// If largest is not root
if (largest != i)
{
std::swap(arr[i], arr[largest]);
ps += 1;
ks += 1;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// pagr funkcija haep sortui
void heapSort(double arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
std::swap(arr[0], arr[i]);
ks+=1;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
void insertion_sort(double arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
ks+=1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
ks+=1;
ps+=1;
}
arr[j + 1] = key;
ks+=1;
}
}
using namespace std;
double *Data;
double* A;
double* B;
double N;
int main()
{
srand(time(NULL));
cout << "Generuojame atsitktinius duomenis" << endl;
generuoti(20000, "duom.txt");
cout << "Nuskaitome duomenis" << endl;
nuskaityti("duom.txt");
A = new double[(int)N];
B = new double[(int)N];//jeigu algoritmui reikia papildomo masyvo
for (int i = 0; i < N; i++) {
A[i] = Data[i];
}
cout << "Pradine skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
//
insertion_sort(A, N);
//heapSort(A, N);
//truksta veiksmu sk
cout << "Surusiuota skaiciu seka:" << endl;
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << endl;
cout << "Kopijavimu skaicius " << ks << endl;
cout << "Palyginimu skaicius " << ps << endl;
system("pause");
return 0;
}
void generuoti(int _n, const char *_file) {
ofstream os(_file);
os << _n << endl;
for (int i = 0; i<_n; i++)
os << " " << 500+ (double)(rand() % 3001) ;
os.close();
}
void nuskaityti(const char *_file) {
ifstream is(_file);
if (is.fail()) {
cout << "Failo nera" << endl;
exit(1);
}
is >> N;
Data = new double[(int)N];
for (int i = 0; i < N; i++) {
is >> Data[i];
}
}
This is my code, and ps - is equal to a number of comparisons, and ks - is equal to number of copying. I want to ask if I counted all comparisons and all copying in the algorithms? Thanks for answers.
No
if (l < n && arr[l] > arr[largest])
largest = l;
ps+=1;
There are two problems here. Assuming you are talking about double comparisons (rather than integer), the comparison may or may not occur.
Secondly your indentation is deeply misleading. (You always increment.)
You need
if (l < n) {
ps++; // About to compare
if (arr[l] > arr[largest])
largest = l;
}
There are probably other errors, but it is impossible to tell because I can't read your language, so the printed text, comments, and names are meaningless.
Given you are writing in C++, I would write a class with operator <() and operator =, and a copy constructor, and instrument those. That way you cannot possibly get it wrong.

Inserting element in array

I'm trying to make this program which gets an element from user and inserts it into the made array by user (array must be sorted)
But it doesn't work properly
for example:
a[4]
a[0]=1
a[1]=3
a[2]=5
a[3]=7
then i insert>> 6
but then it goes like this
a[0]=1
a[1]=3
a[2]=5
a[3]=6
a[4]=3866936
the array is able to have upto 100 elements
:|
it's a practice from a book
#include<iostream>
#include<windows.h>
using namespace std;
void insert(int[], int&, int);
int main()
{
const int maxsize = 100;
int a[maxsize];
cout << "build ur array\n"; Sleep(650);
cout << "Enter the number of elements:";
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "a[" << i << "]=";
cin >> a[i];
}
int k;
cout << "Enter a new element:";
cin >> k;
n++;
insert(a, n, k);
for (int i = 0; i < n; i++)
cout << "a[" << i << "]=" << a[i] << endl;
system("pause");
}
void insert(int a[], int& n, int x)
{
for (int i = n - 1; a[i]>x; i--)
a[i] = a[i + 1];
for (int i = n; i <= n; i--)
{
if (x >= a[i])
{
a[i + 1] = x;
break;
}
}
Assuming you know what you're doing ex. no one can enter more than 99, assuming you will check if the value is less than 100, you have only one error in insert:
a[i] = a[i+1];
should be
a[i+1] = a[i];
The full function should look like this to work with all possible cases:
void insert(int a[], int& n, int x)
{
for (int i = n - 2; a[i]>x && i >= 0; i--)
a[i+1] = a[i];
for (int i = n-2; i >= 0; i--)
{
if (x >= a[i])
{
a[i + 1] = x;
return;
}
}
a[0] = x;
}
You are experiencing undefined behavior due to the fact that you are reading from outside of the array bounds (0 - 3). You should use an std::vector for dynamically sized arrays:
std::vector<int> vec;
vec.push_back(1);
vec.push_back(3);
vec.push_back(5);
vec.push_back(7);
and then:
vec.push_back(6);
Later on, if you want to sort the array you can just do:
std::sort(vec.begin(), vec.end());
You just need to remember that index of array starts from 0. When you want to have 4 elements array int tab[4] you can can read/write elements value using indexes from 0 to 3 tab[0], tab[1], tab[2], tab[3]. Element tab[4] is not part of your array and when you want to read element from your such place, you will get value that is already there (you can think about it as unpredictable random value, but it is not true random value).
By the way, you question is about C language. If you using C++, read about containers like std::array, std::vector etc.
With some stuff from STL, you may use the following:
class SortedVector
{
public:
using const_iterator = std::vector<int>::const_iterator;
void insert(int value) {
auto it = std::lower_bound(v.begin(), v.end(), value);
v.insert(it, value);
}
const_iterator begin() const { return v.begin(); }
const_iterator end() const { return v.end(); }
private:
std::vector<int> v;
};
Live Example
std::vector is the container.
std::lower_bound finds the location where to insert (the way that insertion is still in order)
std::vector::insert does the insertion (which the shifting of the element).
if you don't want to use std::vector and us C-array: you may use:
void insert(int a[], int& n, int x)
{
auto it = std::lower_bound(a, a + n, x);
std::copy(it, a + n, it + 1);
*it = x;
++n;
}
Live example.
>
with help of prajmus
i solved the problem
:
#include<iostream>
#include<windows.h>
using namespace std;
void insert(int[], int&, int);
int main()
{
const int maxsize = 100;
int a[maxsize];
cout << "build ur array\n"; Sleep(650);
cout << "Enter the number of elements:";
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "a[" << i << "]=";
cin >> a[i];
}
int k;
cout << "Enter a new element:";
cin >> k;
n++;
insert(a, n, k);
for (int i = 0; i < n; i++)
cout << "a[" << i << "]=" << a[i] << endl;
system("pause");
}
void insert(int a[], int& n, int x)
{
for (int i = n - 2; a[i]>x; i--)
a[i+1] = a[i];
for (int i = n-1; i <= n; i--)
{
if (x >= a[i])
{ a[i + 1] = x;
break;
}
}
}

implementing merge sort in C++

I have studied the theory of the merge sort but don't have any idea of how to implement it in C++. My question is, merge sort creates arrays in recursion. But when implementing, how do we create arrays in runtime? or what is the general approach for this?
Thanks.
To answer the question: Creating dynamically sized arrays at run-time is done using std::vector<T>. Ideally, you'd get your input using one of these. If not, it is easy to convert them. For example, you could create two arrays like this:
template <typename T>
void merge_sort(std::vector<T>& array) {
if (1 < array.size()) {
std::vector<T> array1(array.begin(), array.begin() + array.size() / 2);
merge_sort(array1);
std::vector<T> array2(array.begin() + array.size() / 2, array.end());
merge_sort(array2);
merge(array, array1, array2);
}
}
However, allocating dynamic arrays is relatively slow and generally should be avoided when possible. For merge sort you can just sort subsequences of the original array and in-place merge them. It seems, std::inplace_merge() asks for bidirectional iterators.
Based on the code here: http://cplusplus.happycodings.com/algorithms/code17.html
// Merge Sort
#include <iostream>
using namespace std;
int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid = low + (high-low)/2; //This avoids overflow when low, high are too large
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{
int num,i;
cout<<"*******************************************************************
*************"<<endl;
cout<<" MERGE SORT PROGRAM
"<<endl;
cout<<"*******************************************************************
*************"<<endl;
cout<<endl<<endl;
cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN
PRESS
ENTER]:"<<endl;
cin>>num;
cout<<endl;
cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN
PRESS ENTER]:"<<endl;
for(i=1;i<=num;i++)
{
cin>>a[i] ;
}
merge_sort(1,num);
cout<<endl;
cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
cout<<endl<<endl;
for(i=1;i<=num;i++)
cout<<a[i]<<" ";
cout<<endl<<endl<<endl<<endl;
return 1;
}
I have completed #DietmarKühl s way of merge sort. Hope it helps all.
template <typename T>
void merge(vector<T>& array, vector<T>& array1, vector<T>& array2) {
array.clear();
int i, j, k;
for( i = 0, j = 0, k = 0; i < array1.size() && j < array2.size(); k++){
if(array1.at(i) <= array2.at(j)){
array.push_back(array1.at(i));
i++;
}else if(array1.at(i) > array2.at(j)){
array.push_back(array2.at(j));
j++;
}
k++;
}
while(i < array1.size()){
array.push_back(array1.at(i));
i++;
}
while(j < array2.size()){
array.push_back(array2.at(j));
j++;
}
}
template <typename T>
void merge_sort(std::vector<T>& array) {
if (1 < array.size()) {
std::vector<T> array1(array.begin(), array.begin() + array.size() / 2);
merge_sort(array1);
std::vector<T> array2(array.begin() + array.size() / 2, array.end());
merge_sort(array2);
merge(array, array1, array2);
}
}
I've rearranged the selected answer, used pointers for arrays and user input for number count is not pre-defined.
#include <iostream>
using namespace std;
void merge(int*, int*, int, int, int);
void mergesort(int *a, int*b, int start, int end) {
int halfpoint;
if (start < end) {
halfpoint = (start + end) / 2;
mergesort(a, b, start, halfpoint);
mergesort(a, b, halfpoint + 1, end);
merge(a, b, start, halfpoint, end);
}
}
void merge(int *a, int *b, int start, int halfpoint, int end) {
int h, i, j, k;
h = start;
i = start;
j = halfpoint + 1;
while ((h <= halfpoint) && (j <= end)) {
if (a[h] <= a[j]) {
b[i] = a[h];
h++;
} else {
b[i] = a[j];
j++;
}
i++;
}
if (h > halfpoint) {
for (k = j; k <= end; k++) {
b[i] = a[k];
i++;
}
} else {
for (k = h; k <= halfpoint; k++) {
b[i] = a[k];
i++;
}
}
// Write the final sorted array to our original one
for (k = start; k <= end; k++) {
a[k] = b[k];
}
}
int main(int argc, char** argv) {
int num;
cout << "How many numbers do you want to sort: ";
cin >> num;
int a[num];
int b[num];
for (int i = 0; i < num; i++) {
cout << (i + 1) << ": ";
cin >> a[i];
}
// Start merge sort
mergesort(a, b, 0, num - 1);
// Print the sorted array
cout << endl;
for (int i = 0; i < num; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
#include <iostream>
using namespace std;
template <class T>
void merge_sort(T array[],int beg, int end){
if (beg==end){
return;
}
int mid = (beg+end)/2;
merge_sort(array,beg,mid);
merge_sort(array,mid+1,end);
int i=beg,j=mid+1;
int l=end-beg+1;
T *temp = new T [l];
for (int k=0;k<l;k++){
if (j>end || (i<=mid && array[i]<array[j])){
temp[k]=array[i];
i++;
}
else{
temp[k]=array[j];
j++;
}
}
for (int k=0,i=beg;k<l;k++,i++){
array[i]=temp[k];
}
delete temp;
}
int main() {
float array[] = {1000.5,1.2,3.4,2,9,4,3,2.3,0,-5};
int l = sizeof(array)/sizeof(array[0]);
merge_sort(array,0,l-1);
cout << "Result:\n";
for (int k=0;k<l;k++){
cout << array[k] << endl;
}
return 0;
}
The problem with merge sort is the merge, if you don't actually need to implement the merge, then it is pretty simple (for a vector of ints):
#include <algorithm>
#include <vector>
using namespace std;
typedef vector<int>::iterator iter;
void mergesort(iter b, iter e) {
if (e -b > 1) {
iter m = b + (e -b) / 2;
mergesort(b, m);
mergesort(m, e);
inplace_merge(b, m, e);
}
}
I know this question has already been answered, but I decided to add my two cents. Here is code for a merge sort that only uses additional space in the merge operation (and that additional space is temporary space which will be destroyed when the stack is popped). In fact, you will see in this code that there is not usage of heap operations (no declaring new anywhere).
Hope this helps.
void merge(int *arr, int size1, int size2) {
int temp[size1+size2];
int ptr1=0, ptr2=0;
int *arr1 = arr, *arr2 = arr+size1;
while (ptr1+ptr2 < size1+size2) {
if (ptr1 < size1 && arr1[ptr1] <= arr2[ptr2] || ptr1 < size1 && ptr2 >= size2)
temp[ptr1+ptr2] = arr1[ptr1++];
if (ptr2 < size2 && arr2[ptr2] < arr1[ptr1] || ptr2 < size2 && ptr1 >= size1)
temp[ptr1+ptr2] = arr2[ptr2++];
}
for (int i=0; i < size1+size2; i++)
arr[i] = temp[i];
}
void mergeSort(int *arr, int size) {
if (size == 1)
return;
int size1 = size/2, size2 = size-size1;
mergeSort(arr, size1);
mergeSort(arr+size1, size2);
merge(arr, size1, size2);
}
int main(int argc, char** argv) {
int num;
cout << "How many numbers do you want to sort: ";
cin >> num;
int a[num];
for (int i = 0; i < num; i++) {
cout << (i + 1) << ": ";
cin >> a[i];
}
// Start merge sort
mergeSort(a, num);
// Print the sorted array
cout << endl;
for (int i = 0; i < num; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
Here's a way to implement it, using just arrays.
#include <iostream>
using namespace std;
//The merge function
void merge(int a[], int startIndex, int endIndex)
{
int size = (endIndex - startIndex) + 1;
int *b = new int [size]();
int i = startIndex;
int mid = (startIndex + endIndex)/2;
int k = 0;
int j = mid + 1;
while (k < size)
{
if((i<=mid) && (a[i] < a[j]))
{
b[k++] = a[i++];
}
else
{
b[k++] = a[j++];
}
}
for(k=0; k < size; k++)
{
a[startIndex+k] = b[k];
}
delete []b;
}
//The recursive merge sort function
void merge_sort(int iArray[], int startIndex, int endIndex)
{
int midIndex;
//Check for base case
if (startIndex >= endIndex)
{
return;
}
//First, divide in half
midIndex = (startIndex + endIndex)/2;
//First recursive call
merge_sort(iArray, startIndex, midIndex);
//Second recursive call
merge_sort(iArray, midIndex+1, endIndex);
merge(iArray, startIndex, endIndex);
}
//The main function
int main(int argc, char *argv[])
{
int iArray[10] = {2,5,6,4,7,2,8,3,9,10};
merge_sort(iArray, 0, 9);
//Print the sorted array
for(int i=0; i < 10; i++)
{
cout << iArray[i] << endl;
}
return 0;
}
This would be easy to understand:
#include <iostream>
using namespace std;
void Merge(int *a, int *L, int *R, int p, int q)
{
int i, j=0, k=0;
for(i=0; i<p+q; i++)
{
if(j==p) //When array L is empty
{
*(a+i) = *(R+k);
k++;
}
else if(k==q) //When array R is empty
{
*(a+i) = *(L+j);
j++;
}
else if(*(L+j) < *(R+k)) //When element in L is smaller than element in R
{
*(a+i) = *(L+j);
j++;
}
else //When element in R is smaller or equal to element in L
{
*(a+i) = *(R+k);
k++;
}
}
}
void MergeSort(int *a, int len)
{
int i, j;
if(len > 1)
{
int p = len/2 + len%2; //length of first array
int q = len/2; //length of second array
int L[p]; //first array
int R[q]; //second array
for(i=0; i<p; i++)
{
L[i] = *(a+i); //inserting elements in first array
}
for(i=0; i<q; i++)
{
R[i] = *(a+p+i); //inserting elements in second array
}
MergeSort(&L[0], p);
MergeSort(&R[0], q);
Merge(a, &L[0], &R[0], p, q); //Merge arrays L and R into A
}
else
{
return; //if array only have one element just return
}
}
int main()
{
int i, n;
int a[100000];
cout<<"Enter numbers to sort. When you are done, enter -1\n";
i=0;
while(true)
{
cin>>n;
if(n==-1)
{
break;
}
else
{
a[i] = n;
i++;
}
}
int len = i;
MergeSort(&a[0], len);
for(i=0; i<len; i++)
{
cout<<a[i]<<" ";
}
return 0;
}
This is my version (simple and easy):
uses memory only twice the size of original array.
[ a is the left array ] [ b is the right array ] [ c used to merge a and b ] [ p is counter for c ]
void MergeSort(int list[], int size)
{
int blockSize = 1, p;
int *a, *b;
int *c = new int[size];
do
{
for (int k = 0; k < size; k += (blockSize * 2))
{
a = &list[k];
b = &list[k + blockSize];
p = 0;
for (int i = 0, j = 0; i < blockSize || j < blockSize;)
{
if ((j < blockSize) && ((k + j + blockSize) >= size))
{
++j;
}
else if ((i < blockSize) && ((k + i) >= size))
{
++i;
}
else if (i >= blockSize)
{
c[p++] = b[j++];
}
else if (j >= blockSize)
{
c[p++] = a[i++];
}
else if (a[i] >= b[j])
{
c[p++] = b[j++];
}
else if (a[i] < b[j])
{
c[p++] = a[i++];
}
}
for (int i = 0; i < p; i++)
{
a[i] = c[i];
}
}
blockSize *= 2;
} while (blockSize < size);
}