-
my recursive logic
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] << " ";
}
-
Just a quick note, instead of:
Code:
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;
You can use:
Code:
int array[MAX] = {2, 3, 1, 2, 134, 2, 13, 343, 1111, 1, 0};
That wouldn't cause an error though. As far as I can tell, it seems okay. Maybe somebody else will be able to point out where it's going wrong, but I can't...When added it to the other program, was it just a matter of it not sorting properly? Or did something else not work?...
-
ya it was a pain, apvector was used so i had to change some things, and adapt it to the programs environment. so it didnt sort correctly thats probably where the problem is. thanks.