Please help: [Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings] - c++

this is my first time here and I'm in a bit of a pickle. I have an assignment in class that asks the user which sorting algorithm do they want to sort in and my professor gave us a skeleton of the program already and all we have to do is to write the code of 3 sorting algorithms. It says that in line 41 I'm trying to pass a string with a char data type (my professor wrote that) and I'm stumped on how to fix it because I looked through the similar forum posts with people who have the same error as I and the solutions didn't work. Could you please take a look at the program to see what's wrong and how to fix it? I would deeply appreciate it.
#include <stdlib.h>
#include <time.h>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 1000000;
// Set this to true if you wish the arrays to be printed.
const bool OUTPUT_DATA = false;
void ReadInput(string& sortAlg, int& size);
void GenerateSortedData(int data[], int size);
void GenerateReverselySortedData(int data[], int size);
void GenerateRandomData(int data[], int size);
void GenerateNearlySortedData(int data[], int size);
void Sort(int data[], int size, string sortAlg, char* dataType);
void InsertionSort(int data[], int size);
void MergeSort(int data[], int lo, int hi);
void combine(int data[], int size, int lo, int hi, int mid);
void QuickSort(int data[], int lo, int hi);
int partition(int data[], int lo, int hi);
void Swap(int &x, int &y);
bool IsSorted(int data[], int size);
void printData(int data[], int size, string title);
int main(void)
{
int size;
string sortAlg;
ReadInput(sortAlg, size);
int * data = new int[size];
GenerateSortedData(data, size);
Sort(data, size, sortAlg, "Sorted Data");
GenerateReverselySortedData(data, size);
Sort(data, size, sortAlg, "Reversely Sorted Data");
GenerateRandomData(data, size);
Sort(data, size, sortAlg, "Random Data");
GenerateNearlySortedData(data, size);
Sort(data, size, sortAlg, "Nearly Sorted Data");
cout << "\nProgram Completed Successfully." << endl;
return 0;
}
/********************************************************************/
void ReadInput(string& sortAlg, int& size)
{
cout << " I:\tInsertion Sort" << endl;
cout << " M:\tMergeSort" << endl;
cout << " Q:\tQuickSort" << endl;
cout << "Enter sorting algorithm: ";
cin >> sortAlg;
string sortAlgName;
if(sortAlg == "I")
sortAlgName = "Insertion Sort";
else if(sortAlg == "M")
sortAlgName = "MergeSort";
else if(sortAlg == "Q")
sortAlgName = "QuickSort";
else {
cout << "\nUnrecognized sorting algorithm Code: " << sortAlg << endl;
exit(1);
}
cout << "Enter input size: ";
cin >> size;
if(size < 1 || size > MAX_SIZE)
{
cout << "\nInvalid input size " << size
<< ". Size should be between 1 and " << MAX_SIZE << endl;
exit(1);
}
cout << "\nSorting Algorithm: " << sortAlgName;
cout << "\nInput Size = " << size << endl;
cout << endl;
}
/******************************************************************************/
void GenerateSortedData(int data[], int size)
{
int i;
for(i=0; i<size; i++)
data[i] = i * 3 + 5;
}
/*****************************************************************************/
void GenerateReverselySortedData(int data[], int size)
{
int i;
for(i = 0; i < size; i++)
data[i] = (size-i) * 2 + 3;
}
/*****************************************************************************/
void GenerateRandomData(int data[], int size)
{
int i;
for(i = 0; i < size; i++)
data[i] = rand();
}
/*****************************************************************************/
void GenerateNearlySortedData(int data[], int size)
{
int i;
GenerateSortedData(data, size);
for(i=0; i<size; i++)
if(i % 10 == 0)
if(i+1 < size)
data[i] = data[i+1] + 9;
}
/*****************************************************************************/
void Sort(int data[], int size, string sortAlg, char* dataType)
{
cout << endl << dataType << ":";
if (OUTPUT_DATA)
printData(data, size, "Data before sorting:");
// Sorting is about to begin ... start the timer!
clock_t start = clock();
if(sortAlg == "I")
InsertionSort(data, size);
else if(sortAlg == "M")
MergeSort(data, 0, size-1);
else if(sortAlg == "Q")
QuickSort(data, 0, size-1);
else
{
cout << "Invalid sorting algorithm!" << endl;
exit(1);
}
// Sorting has finished ... stop the timer!
clock_t end = clock();
double elapsed = (((double) (end - start)) / CLOCKS_PER_SEC) * 1000;
if (OUTPUT_DATA)
printData(data, size, "Data after sorting:");
if (IsSorted(data, size))
{
cout << "\nCorrectly sorted " << size << " elements in " << elapsed << "ms";
}
else
cout << "ERROR!: INCORRECT SORTING!" << endl;
cout << "\n-------------------------------------------------------------\n";
}
/*****************************************************************************/
bool IsSorted(int data[], int size)
{
int i;
for(i=0; i<(size-1); i++)
{
if(data[i] > data[i+1])
return false;
}
return true;
}
/*****************************************************************************/
void InsertionSort(int data[], int size)
{
//Write your code here
int i, j, temp;
for(i = 1; i < size; i++) //first element in the array
{
temp = data[i]; //Data[i] values are stored in temp.
while(j > 0 && data[j-1] > data[j]) //While j > 0 and the value of j-1 position is greater
{ //than the value of position j, begin swap.
temp = data[j]; //Value of data[j] is moved to temp.
data[j] = data[j-1]; //The values of data[j-1] is moved to data[j].
data[j-1] = temp; //Then the temp value is moved to the data[j-1] array.
j--; //Decrement j value.
}
}
}
/*****************************************************************************/
void MergeSort(int data[], int size)
{
//Write your code here
int hi, lo, mid;
if(lo <= hi)
{
mid = (hi + lo)/2; //Pivot.
MergeSort(data, lo, mid); //recurssively call lowerhalf of the array.
MergeSort(data, mid+1, hi); //recurssively call upperhalf of the array.
combine(data, size, lo, hi, mid); //combine the array.
}
return;
}
void combine(int data[], int size, int lo, int hi, int mid)
{
int temp[size];
int i = lo;
int j = mid+1;
int k = lo;
for(int i = lo; i <= hi; i++)
{
temp[i] = data[i]; //store the values in data array into the temp array
}
while(i <= mid && j <= hi)
{
if(temp[i] = temp[j]) //if i value in the temp array is equal to the j value in the temp array
{
data[k] = temp[i]; //move the temp[i] values into the main data[k] array
i++; //increment i by 1
}
else
{
data[k] = temp[j]; //otherwise, move the temp[j] values into the main array
j++; //increment j by 1
}
k++;
}
while(i <= mid)
{
data[k] = temp[i]; //while i value is <= to mid value, the temp[i] value is moved to data[k]
k++; //increment k
i++; //increment i
}
}
/*****************************************************************************/
void QuickSort(int data[], int size, int lo, int hi)
{
//Write your code here
int q;
if(lo>=hi)
{
q=partition(data, lo, hi);
QuickSort(data, lo, (q-1));
QuickSort(data, (q+1), hi);
}
}
int partition(int data[], int lo, int hi)
{
int temp; //temp for swaping
int i = lo;
int j = hi;
int pivot = data[(lo+hi)/2]; //pivot takes the end element
while(i<=j)
{
while(data[i] < pivot)
{
i++; //left hand side partition
}
while(data[j] > pivot)
{
j--; //right hand side partition
}
if(i <= j) //swaping occurs
{
temp = data[i]; //take data[i] and put it into temp
data[i] = data[j]; //take array sub data[j] values and put it into array sub data[i]
data[j] = temp; //take the temp values and put it into arra sub data[j]
i++;
j--;
}
}
}
/*****************************************************************************/
void Swap(int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
/*****************************************************************************/
void printData(int data[], int size, string title) {
int i;
cout << endl << title << endl;
for(i=0; i<size; i++)
{
cout << data[i] << " ";
if(i%10 == 9 && size > 10)
cout << endl;
}
}

Character literals are char const(&)[].
So you can't pass them to char*. Instead, pass them as const char*, e.g.:
void Sort(int data[], int size, string sortAlg, const char* dataType)
You also have a variable lenth array (VLA) in line 265. That's a C99/C11 thing, and is not in C++.
The assignment here is wrong:
if(temp[i] = temp[j]) //if i value in the temp array is equal to the j value in the temp array
Write if(temp[i] == temp[j]) to compare ints.
partition (int partition(int data[], int lo, int hi)) has Undefined Behaviour because you don't return a value (and it's used)
You have missing code:
//Write your code here
int hi, lo, mid;
if(lo <= hi)
is also Undefined Behaviour because hi, lo are uninitialized there.
same in void InsertionSort(int data[], int size)
same in void Sort(int*, int, std::string, const char*)
void MergeSort(int data[], int lo, int hi); requires a definition (it's used)
void QuickSort(int data[], int size, int lo, int hi) has a redundant size argument that is not present in the declared prototype (line 27). Remove it
At least compiling code, not done the implementations for you:
Live On Coliru

Related

Sort array using recursion

I have been trying to sort an array using recursion, but I am getting no output, can somebody help me with this, like why there is no output?
void sortarray(int arr[], int index, int key, int len){
if (index == len-2){
}
else{
if (key==len-1){
key=0;
sortarray(arr, index++, key, len );
}
else {
if (arr[key] > arr[key+1]){
swap(arr[key], arr[key+1]);
}
sortarray(arr, index, key++, len );
}
}
}
int main(){
int arr[5] = {5,6,4,3,2};
sortarray(arr, 0,0,5);
for(int i=0; i<5; i++){
cout << arr[i] << " ";
}
}
I fixed the segfault and simplified the code to make it more clear what it does. Namely, walks the array once and swap the key with the next if it's larger. This is not a valid sort algorithm:
#include <iostream>
using namespace std;
void sortarray(int arr[], int key, int len) {
// base case
if (key + 1 == len) return;
// recursive case
if (arr[key] > arr[key + 1]){
swap(arr[key], arr[key + 1]);
}
sortarray(arr, key + 1, len );
}
int main() {
int arr[] = {5,6,4,3,2};
int len = sizeof(arr) / sizeof(*arr);
sortarray(arr, 0, len);
for(int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
return 0;
}
and the result is:
5 4 3 2 6
I made some edits to your code and it works now (don't mind the printArr function, it's there just because cycles in main are ugly):
#include <iostream>
using namespace std;
void printArr(int arr[], int size)
{
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void sortarray(int arr[], int index, int key, int len)
{
if (index < len)
{
if (key == len - 1) {
key = 0;
sortarray(arr, ++index, key, len);
}
else {
if (arr[key] > arr[key + 1]) {
swap(arr[key], arr[key + 1]);
}
sortarray(arr, index, ++key, len);
}
}
}
int main()
{
int arr[5] = { 5,6,4,3,2 };
cout << "Before sort:" << endl;
printArr(arr, sizeof(arr)/sizeof(*arr));
sortarray(arr, 0, 0, 5);
cout << "After sort:" << endl;
printArr(arr, sizeof(arr) / sizeof(*arr));
return 0;
}
So the first problem was missing iostream and std namespace.
Key changes in the algorithm itself were:
change argument++ to ++argument
change the first condition to (index < len)
As to why your code didn't work properly: the index missed the stopping condition and went over the value of len (thus the screen o' fives).
So this answers your question, but this algorithm you wrote breaks once there are two same values next to each other. There is a good reason we use cycles for sorting and unless recursion is the point, I would recommend abandoning it for this task.
This code works perfectly-:
void sortArr(int arr[],int index, int key, int len){
// static int index = 0;
// static int key = 0;
if (index == len-1){
}
else{
if (key==len-1){
key=0;
sortArr(arr,index+1,key,len );
}
else {
if (arr[key] > arr[key+1]){
swap(arr[key], arr[key+1]);
}
sortArr(arr, index, key+1 ,len );
}
}
}
int main(){
int arr[5] = {5,6,4,3,2};
sortarray(arr, 0, 5);
for(int i=0; i<5; i++) {
cout << arr[i] << " ";
}
return 0;
}
The output of the code is:
2 3 4 5 6

Can't figure out why my Print Array is replacing elements

I'm taking a C++ class and we've gotten to pointers. The assignment we've been given is to basically bubble sort an array that was read from a text file by passing pointers as parameters for various functions. I think I have a decent setup that outputs what I'm looking for, but for specific actions, I'm getting a zero as an element when there isn't one written to the array.
#include <iostream>
#include <fstream>
using namespace std;
int capacity;
int count;
int readData(int *&arr);
void swap(int *xp, int *yp);
void bsort(int *arr, int last);
void writeToConsole(int *arr, int last);
void bubble_sort(int *arr, int last, int(*ptr)(int, int));
int ascending(int a, int b);
int descending(int a, int b);
int main() {
int *whatever = NULL;
count = readData(whatever);
cout << "Raw array data:" << endl;
writeToConsole(whatever, capacity);
cout << "After simple bubble sort:" << endl;
bubble_sort(whatever, capacity, ascending);
writeToConsole(whatever, capacity);
cout << "Now descending:" << endl;
bubble_sort(whatever, capacity, descending);
writeToConsole(whatever, capacity);
return 0;
}
int readData(int *&arr) {
ifstream inputFile;
inputFile.open("data.txt");
if (!inputFile) {
cout << "Error!";
}
inputFile >> capacity;
arr = new int[capacity];
for(int i = 0; i < capacity; i++){
inputFile >> arr[i];
}
inputFile.close();
return capacity;
}
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bsort(int *arr, int last) {
int i, j;
bool swapped;
for (i = 0; i < last + 1; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
void writeToConsole(int *arr, int last) {
cout << "[ ";
for(int i = 0; i < last; i++){
cout << arr[i] << " ";
}
cout << "]" << endl;
}
void bubble_sort(int *arr, int last, int(*ptr)(int, int)){
int i, j;
bool swapped;
for (i = 0; i < last; i++)
{
swapped = false;
for (j = 0; j < last-i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j] , arr[j+1]))
{
swap(arr[j], arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
int ascending(int a, int b){
return a > b;
}
int descending(int a, int b){
return a < b;
}
My output looks like this:
Raw array data:
[ 8 4 7 2 9 5 6 1 3 ]
After simple bubble sort:
[ 0 1 2 3 4 5 6 7 8 ]
Now descending:
[ 9 8 7 6 5 4 3 2 1 ]
Any ideas as to why my second sort is throwing in a zero? Thank you!
you have to do this change is in bubble_sort function
for (j = 1; j < last - i; j++)
{
//Use the function pointer to determine which logic to use
if (ptr(arr[j-1], arr[j]))
{
swap(arr[j-1], arr[j]);
swapped = true;
}
}

Obtaining Large Signed Value in my QuickSort/InsertionSort Algorithm

so my code is essentially working; however, I need clarification as to why when I implement insertion sort when I get to less than 20 elements in a subarray it adds a large signed value at the end when I print them out.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partitionMiddle (int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void chooseMiddle....
void chooseMedian{code here...}
void insertionSort(int arr[], int low, int high){
int j;
for(int i = low+1; i <= high; i++){
j = i;
while(j>low && arr[j-1]> arr[j]){
swap(arr[j], arr[j-1]);
j= j-1;
}
}
}
void quickSortMiddle(int arr[], int low, int high)
{
int pi = partitionMiddle(arr, low, high);
if (high-low > 20)
{
quickSortMiddle(arr, low, pi - 1);
quickSortMiddle(arr, pi + 1, high);
}
else {
insertionSort(arr, low, pi);
insertionSort(arr, pi+1, high);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
}
int main()
{
clock_t x, k;
x = clock();
int arr[10000];
srand((unsigned)time(0));
for(int i =0; i<10000; i++) {
arr[i] = (rand()%100)+1;
}
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Original array: " ;
printArray(arr, n);
cout << endl;
cout << "With Insertion Sort & Middle Element";
chooseMiddle(arr, 0, n-1);
quickSortMiddle(arr, 0, n-1);
cout << endl;
k = clock();
// can comment this one vvvv or the previous one out to try them both
cout << "With Insertion Sort & Median Element";
chooseMedian(arr, 0, arr[((n-1)/2)], n-1);
quickSortMiddle(arr, 0, n-1);
cout << endl;
k = clock();
printf("Sorted array: ");
printArray(arr, n);
cout << endl;
cout << "CPU Time : ";
cout << k-x;
cout << endl << endl;
return 0;
}
My expected results were to not just have -272632368 at the very end of my sorted array when I print it out. I think I went out of bounds in my insertion sort algorithm but I'm not sure as to where. Maybe someone with a better eye can catch it.
**** EDIT...So I went to debug the code on my own and it the number was appearing there somehow having to do with the n-1 parameter when I was calling the chooseMedian/chooseMiddle or quickSortMiddle functions. I changed it to simply being 'n'. I don't get why, but it's working now. If someone can explain why, that'd be helpful, but if not, that's okay too.
****EDIT2...So now that I have your attention, can you please explain to me why using pointers in the swap function is better than not? I found this example of a swap function online and don't know why they used pointers.

Calling function from one class in another in C++

So, I am writing a program in C++ that has a function in the Sort class that I wish to call in the Main class. The function has several data members used that are present in that class, that are not present in the Main class and I keep getting a C2660 error, that "Function does not take 0 arguments". Is there a way (short of writing a bunch of getters and setters) to resolve this?
#include "Sort.h"
#include "Timer.h"
using namespace std;
int main
{
Sort *sort = new Sort();
Timer ti;
sort->SetRandomSeed(12345);
sort->InitArray();
cout << "starting InsertionSort" << endl;
ti.Start();
sort->InsertionSort();
ti.End();
cout << "Insertion sort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
//sort->InitList();
//cout << "starting InsertionSortList()" << endl;
//ti.Start();
//sort->InsertionSortList();
//ti.End();
//cout << "Insertion sort list duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting SelectionSort" << endl;
ti.Start();
sort->SelectionSort();
ti.End();
cout << "SelectionSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting MergeSort" << endl;
ti.Start();
sort->MergeSort();
ti.End();
cout << "MergeSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting QuickSort" << endl;
ti.Start();
sort->QuickSort();
ti.End();
cout << "QuickSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitVector();
cout << "starting std::sort() of Vector<int>" << endl;
ti.Start();
sort->VectorSort();
ti.End();
cout << "std::sort() duration: " << ti.DurationInNanoSeconds() << "ns" << endl;
delete sort;
cout << endl <<"Press [Enter] key to exit";
getchar();
}
Sort.cpp
//const int for array
int num = 10000000;
int val = 10000;
//array
int *tmpArray, *qArr, *insArr, *selArr, *mergArr = NULL;
int low, high;
//duration for timer
int duration = 0;
Sort::Sort()
{
}
Sort::~Sort()
{
}
void Sort::InitArray()
{
//int for index
int i = 0;
tmpArray = new int[num];
qArr = new int[num];
insArr = new int[num];
selArr = new int[num];
mergArr = new int[num];
//fill temp array with sequential numbers
for (int i = 0; i < num; i++)
{
tmpArray[i] = 1 + rand() % val;
}
for (i = 0; i < num; i++)
{
qArr[i] = tmpArray[i];
insArr[i] = tmpArray[i];
selArr[i] = tmpArray[i];
mergArr[i] = tmpArray[i];
}
low = qArr[0];
high = qArr[num - 1];
int n = sizeof(tmpArray) / sizeof(tmpArray[0]);
}
void Sort::InitVector()
{
vector<int> v(num);
std::generate(v.begin(), v.end(), std::rand);
}
void Sort::InitList()
{
// A set to store values
std::list<int> l;
// Loop until we get 50 unique random values
while (l.size() < num)
{
l.push_back(1 + rand() % val);
}
for (int n : l) {
std::cout << n << '\n';
}
}
//setting seed
void Sort::SetRandomSeed(unsigned int seed)
{
seed = rand();
}
void Sort::InsertionSort()
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = insArr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && insArr[j] > key)
{
insArr[j + 1] = insArr[j];
j = j - 1;
}
insArr[j + 1] = key;
}
delete[] insArr;
insArr = NULL;
}
int Sort::partition(int qArr[], int low, int high)
{
int pivot = qArr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (qArr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&qArr[i], &qArr[j]);
}
}
swap(&qArr[i + 1], &qArr[high]);
return (i + 1);
}
void Sort::QuickSort(int qArr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(qArr, low, high);
// Separately sort elements before
// partition and after partition
QuickSort(qArr, low, pi - 1);
QuickSort(qArr, pi + 1, high);
}
delete[] qArr;
qArr = NULL;
}
void Sort::SelectionSort()
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (selArr[j] < selArr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&selArr[min_idx], &selArr[i]);
}
delete[] selArr;
selArr = NULL;
}
void Sort::swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void Sort::VectorSort()
{
std::sort(v.begin(), v.end());
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void Sort::merge(int mergArr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int* L;
int* R;
/* create temp arrays */
L = new int[n1];
R = new int[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = mergArr[l + i];
for (j = 0; j < n2; j++)
R[j] = mergArr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
mergArr[k] = L[i];
i++;
}
else
{
mergArr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
mergArr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
mergArr[k] = R[j];
j++;
k++;
}
}
void Sort::MergeSort(int mergArr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
MergeSort(mergArr, l, m);
MergeSort(mergArr, m + 1, r);
merge(mergArr, l, m, r);
}
delete[] mergArr;
mergArr = NULL;
}
Sort.h
#include <iomanip>
#include <fstream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include<list>
using namespace std;
#pragma once
class Sort
{
public:
Sort();
~Sort();
void InitArray();
void InitVector();
void InitList();
void SetRandomSeed(unsigned int seed);
int n, right, left, l, r, m;
vector<int> v;
void InsertionSort();
int partition(int qArr[], int low, int high);
void QuickSort(int qArr[], int low, int high);
void swap(int * xp, int * yp);
void VectorSort();
void MergeSort(int arr[], int l, int r);
void merge(int arr[], int l, int m, int r);
void SelectionSort();
};
Ignoring the Timer class (those are all good) here is the rest of the code. The C2660 errors are shown for the sort->MergeSort() and sort->QuickSort() calls in main.
I resolved the issues myself. I created helper functions in the Sort class that have no arguments and call the functions themselves to use in the main. Helper Functions shown below.
Sort.cpp
//method for Main to run to prevent C2660 errors
void Sort::mergeHelper()
{
MergeSort(mergArr, l, r);//call merge sort method
}
//method for Main to run to prevent C2660 errors
void Sort::quickHelper()
{
QuickSort(qArr, low, high);//call quick sort method
}
int Main
{
sort->quickHelper();
sort->mergeHelper();
}

C++ : Error in Mergesort using Vector (memory managment)

I am trying to implement merge sort routine in C++ using vectors. But I am getting random numbers after sorting. It doesn't giving any kind of warning either. Please help.
Here is my complete code. I am trying to implement it in a class.
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
class array{
private:
vector<int> num;
public:
array();
void print();
void remove(int element);
void insert(int element);
void sort();
void mergesort(int start, int end);
void merge(int start, int end);
};
array :: array(){
cout << "Enter elements to insert in array(any character to end): ";
int element;
while(cin >> element)
num.push_back(element);
// clearing the input(cin) buffer
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
void array :: print(){
for(unsigned int i = 0; i < num.size(); i++)
cout << "Element " << i+1 << ": " << num[i] << endl;
}
void array :: remove(int element){
for(unsigned int i = 0; i< num.size(); i++)
if(num[i] == element){
num.erase(num.begin()+i,num.begin()+i+1);
break;
}
}
void array :: insert(int element){
num.push_back(element);
}
void array :: sort(){
if(num.size() <= 1)
return;
else
mergesort(0, num.size()-1);
}
void array :: mergesort(int start, int end){
if(start >= end)
return;
else{
int mid = (start + end)/2;
mergesort(start, mid);
mergesort(mid+1, end);
merge(start, end);
}
}
void array :: merge(int start, int end){
vector<int> num2;
int mid = (start + end)/2;
int i = start;
int j = mid + 1;
cout << "start: " << start << " mid: " << mid << " end: " << end << endl;
while(i <= mid && j <= end)
num2.push_back(num[i] >= num[j] ? num[j++]: num[i++]);
if(i > mid)
while(j <= end)
num2.push_back(num[j++]);
else
while(i <= mid)
num2.push_back(num[i++]);
for(unsigned int i = 0; i <= num.size(); i++)
num[i] = num2[i];
}
The most obvious issue is the last loop in merge()
for(unsigned int i = 0; i <= num.size(); i++)
num[i] = num2[i];
Indexes start and end are passed to the function but this code blindly tries to copy num.size()+1 elements from your temporary vector to the beginning of num. I think something like this is more correct:
for(unsigned int i = 0; i < num2.size(); i++)
num[start + i] = num2[i];
What "warning" were you expecting from a syntactically correct C++ program? As long as the syntax is correct, you won't get any "warning".
So what debugging have you done? That is the first thing you should do.