I was wondering if my logic was correct here, or if there are some things to change, with the given numbers the program works fine. but then i tried to add it to another program that chooses which type of sort algorithm to use and it wouldnt work for beans.
Code:
#include <iostream>
using namespace std;
const int MAX = 10+1;
void mergeSort (int [MAX], int , int);
void merge (int [MAX], int, int, int);
void print (const int [MAX]);
main()
{
int array[MAX];
array[0] = 2; array[1] = 3; array[2] = 1; array[3] = 2;
array[4] = 134; array[5] = 2; array[6] = 13; array[7] = 343;
array[8] = 1111; array[9] = 1; array[10] = 0;
mergeSort (array, 1, MAX - 1);
print (array);
system("pause");
}
void mergeSort (int array[MAX], int first, int last)
{
int mid;
if (first < last)
{
mid = (first + last) / 2;
mergeSort (array, first, mid);
mergeSort (array, mid+1, last);
merge (array, first, mid, last);
}
}
void merge (int array[MAX], int first, int mid, int last)
{
const int SIZE = (last - first) + 1;
int temp[SIZE];
int tIndex = 0, left = first, right = mid+1;
while (left <= mid && right <= last)
{
if (array[left] <= array[right])
temp[tIndex++] = array[left++];
else
temp[tIndex++] = array[right++];
}
while (left <= mid) temp[tIndex++] = array[left++];
while (right <= last) temp[tIndex++] = array[right++];
for (int count = 0; count < SIZE; count++)
array[first+count] = temp[count];
}
void print (const int array[MAX])
{
for (int count = 1; count < MAX; count++)
cout << array[count] << " ";
}