Converting User Input from int[] to char[][] - c++

I made this program to take int array as input and sort it using quick sort, but i was wondering, how would i change this program that it takes char[][] as input (string array) and sort them alphabetically?
It works if theres just one string, but i wanna know what if someone wants array of strings
//following program sorts an array using quicksort alorithm
#include<iostream.h>
#include<conio.h>
void swap(int *a, int *b) //function to swap elements
{
int t;
t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int left, int right) //function takes last element as pivot and places all smaller elements on left of pivot and greater elements on right
{
int pivot=arr[right]; //Pivot
int i= (left-1); //index of smaller element
for(int j=left; j<=(right-1); j++)
{
if(arr[j]<=pivot) //if current element is smaller or equal to pivot, theyre swapped
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[right]);
return (i+1);
}
void quicksort(int arr[], int left, int right) //left is starting index, right is last index
{
if(left<right)
{
int index=partition(arr,left,right);
quicksort(arr, left, index-1); //sort elements before and after partition
quicksort(arr, index+1, right);
}
}
void print(int *arr, int size) //function to print elements in array
{
for(int i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
int n; //to store no. of elements in array
char ch; //ch for choice
do{
int *arr=NULL; //dynamic int array
clrscr();
cout<<"\nEnter Number of Elements:";
cin>>n;
cout<<"\nEnter Elements in Array to be sorted:";
for(int i=0; i<n; i++)
{
cout<<"\nEnter "<<i<<"th element:";
cin>>arr[i];
}
quicksort(arr,0,(n-1));
cout<<"\nSorted Array= ";
print(arr,n);
delete arr;
cout<<"\nwanna sort again??(y/n):";
cin>>ch;
}while(ch=='Y'||ch=='y');
return 0;
}

The integer version in your code needs int *arr = new int[n]; to allocate array of integers.
To do this with array of strings, declare char **arr = new char*[n]; and use strdup to assign array of char to each string.
You should be able to use the standard qsort in older compilers, otherwise use this modified version of your quicksort. The main difference is the replacement of if(arr[j]<=pivot){} with if(strcmp(arr[j], pivot) <= 0){}
void swap(char* &a, char* &b)
{
char *t = a;
a = b;
b = t;
}
int partition(char** arr, int lo, int hi)
{
int i = lo - 1;
for(int j = lo; j < hi - 1; j++)
{
if(strcmp(arr[j], arr[hi]) < 0)
{
i++;
swap(arr[i], arr[j]);
}
}
if(strcmp(arr[hi], arr[i + 1]) < 0)
swap(arr[hi], arr[i + 1]);
return i + 1;
}
void quicksort(char** arr, int const lo, int const hi)
{
if(lo < hi)
{
int p = partition(arr, lo, hi);
quicksort(arr, lo, p);
quicksort(arr, p + 1, hi);
}
}
void print(char **arr, int size)
{
for(int i = 0; i<size; i++)
cout << arr[i] << ", ";
cout << "\n";
}
int main()
{
int n;
cout << "Enter Number of Elements: ";
cin >> n;
cout << "Enter Elements in Array to be sorted:\n";
char buf[255];
char **arr = new char*[n];
for(int i = 0; i < n; i++)
{
cout << "Enter " << i << "th element: ";
cin >> buf;
arr[i] = strdup(buf);
}
quicksort(arr, 0, (n - 1));
cout << "Sorted:\n";
print(arr, n);
cout << "\n";
for(int i = 0; i < n; i++)
free(arr[i]); //<=== edit**
delete[]arr;
return 0;
}
Edit 1: changed quicksort function
Edit 2: changed the cleanup. strdup has to be cleaned up with free

Related

Why is this recursive selection sort not working

I tried to run the code but it just gets stuck. NO error no warning nothing.Is there a better way to write a recursive selection sort?
#include <iostream>
using namespace std;
void scan(int *arr, int size){
for(int i = 0; i < size; i++){
cin >> arr[i];
}
}
void print(int *arr, int size){
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
cout << "\n";
}
void swap(int *p1, int *p2){
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void insertion(int *arr, int size){
if(size <= 1)return;
int i, max = size - 1;
for(int i = 0; i < size; i++){
if(arr[i] > arr[max])max = i;
}
swap(&arr[max], &arr[i]);
insertion(arr, size - 1);
}
int main(){
int *arr;
int size;
cout << "Enter the size of the array - ";
cin >> size;
arr = (int*)malloc(size*sizeof(int));
cout << "Enter the elements of the array - ";
scan(arr, size);
print(arr, size);
insertion(arr, size);
print(arr, size);
}
I feel like there is something wrong with the base case of the recursion. How do you generally solve these types of problems.
There was 1 small problem in your code. When you call the swap function in the insertion function you have to call it with &arr[max] and &arr[size-1], you can also use i-1, as the value of i is size here.
Code Attached for insertion function
void insertion(int *arr, int size){
if(size <= 1)return;
int i, maxIndex = 0;
for(i = 0; i < size; i++){
if(arr[i] > arr[maxIndex]) maxIndex = i;
}
swap(&arr[maxIndex], &arr[size-1]);
insertion(arr, size - 1);
}
The way to debug are many, you can learn to use the gnu debugger which is gdb or use print statements to find out where your code is going wrong.

Merge Sort: segmentation fault 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.

Bubble sort with array size

I want to do bubble sort for n elements of arraylist. Instead of declaring the arraylist first like below, I want to create the arraylist using for loops.
So this is the code of declaring the arraylist first:
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n-1; i++) {
swapped = false;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = 5;
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
}
which I do not want to do.
I have made this, but I do not know why it does not work. I'm still quite new with C++. May I know what's the problem. Thank you so much.
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n-1; i++) {
swapped = false;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
There are two problems:
Arrays are 0-indexed.
Variable length array which is not really legal in C++.
So write main like:
// Driver code
int main()
{
int n = 5;
int* arr = new int[n];
for(int i=0; i<n; i++){
arr[i]=i+1;
cout<<arr[i];
cout<<endl;
}
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
delete[] arr;
}

Why am i getting a runtime error after giving input for array and entering mergesort function?

#include<iostream>
using namespace std;
void merge(int *lArray, int nL, int *rArray, int nR, int *Array){
int i,j,k;
i=0; j=0; k=0;
//i,j,k are pointers for lArray, rArray & Array
// nL & nR are numbr of elements in lArray & rArray respectively
while(i<nL && j<nR)
{
if(lArray[i] <= rArray[j])
Array[k++] = lArray[i++];
else
Array[k++] = rArray[j++];
}
while(i<nL)
Array[k++] = lArray[i++];
while(i<nR)
Array[k++] = rArray[j++];
return;
}
void mergesort(int *Array, int n)
{
if (n<2)
return;
int mid = n/2;
int lArray[mid];
int rArray[n-mid];
for (int i=0;i<mid;i++)
lArray[i] = Array[i];
for (int i=mid;i<n;i++)
rArray[i-mid] = Array[i];
mergesort(lArray, mid);
mergesort(rArray,n-mid);
merge(lArray,mid,rArray,n-mid,Array);
delete(lArray);
delete(rArray);
}
int main()
{
int Array[10];
int n = 10;
cout<< "Enter Values :" << " ";
for(int i=0; i<10; i++)
cin>>Array[i];
mergesort(Array,n);
for(int i=0; i<n; i++)
cout<<Array[i]<< " ";
return 0;
}
Its a simple merge sort program but i cant find out where i went wrong.
After running the code i was able to enter the input for array but after entering into mergesort function the console just crashed.
I am using CodeBlocks on 64bit Windows 8.1.
I have done some changes in your mergesort function. Now your program shows the output on console but the output is not sorted. I think there is array indexing problem may be segmentation fault. There is a logical error too in the output.
#include<iostream>
using namespace std;
void merge(int *lArray, int nL, int *rArray, int nR, int *Array)
{
int i,j,k;
i=0; j=0; k=0;
//i,j,k are pointers for lArray, rArray & Array
// nL & nR are numbr of elements in lArray & rArray respectively
while(i<nL && j<nR)
{
if(lArray[i] <= rArray[j])
Array[k++] = lArray[i++];
else
Array[k++] = rArray[j++];
}
while(i<nL)
Array[k++] = lArray[i++];
while(i<nR)
Array[k++] = rArray[j++];
return;
}
void mergesort(int *Array, int n)
{
if(n>2)
{
int mid = (n+1)/2;
int lArray[mid];
int rArray[n-mid];
for (int i=0;i<mid;i++)
lArray[i] = Array[i];
for (int i=mid;i<n;i++)
rArray[i-mid] = Array[i];
mergesort(lArray, mid);
mergesort(rArray,n-mid);
merge(lArray,mid,rArray,n-mid,Array);
delete(lArray);
delete(rArray);
}
}
int main()
{
int Array[10];
int n = 10;
cout<< "Enter Values :" << " ";
for(int i=0; i<10; i++)
cin>>Array[i];
mergesort(Array,n);
for(int i=0; i<10; i++)
cout<<Array[i]<< " ";
return 0;
}

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);
}