0

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

1 Answers1

6

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

sehe
  • 374,641
  • 47
  • 450
  • 633
  • Wow, brilliant. Did you have templates for all these answers? Within 2 minutes, that answer is awesome. – πάντα ῥεῖ Oct 16 '15 at 23:14
  • 2
    @πάνταῥεῖ I don't. I have a compiler with `-Wall` and `-pedantic`. Everyone should use it! – sehe Oct 16 '15 at 23:15
  • Hi! Thank you for commenting and helping find my mistakes. I'm sorry that I sound kind of demanding in my opening because my "Hi everyone, this is..." was cut off. I made some changes you suggested and now it compiles! Thank you so much and now I'm fixing a few more problems like when I use mergesort and after it's done sorting, it crashes and when it show before&after sort, it both shows them sorted already. I'll ask if I get stuck again, thanks! – Steve Tam Oct 17 '15 at 21:00
  • @SteveTam I never said anything about sounding demanding :) If anything, we don't appreciate noise http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be-removed-from-posts – sehe Oct 17 '15 at 21:01