0

For my assignment I need to create a sort_swap function that uses the C++ function swap(); that is already in place. I need to create this so that way it can be used to do other things relating to my program. However, I am not quite sure why my swap function is not working in any of my sorting functions. When printing out the results, I get basically the original list of randomly generated numbers, instead of them being sorted. This program is designed to illustrate and animate the different sorting types, and without the sorting working with my sort_swap functions it is not going to work. I have to keep the sort_swap function.

Any suggestions or recommendations would be appreciated.


#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
#include "rogueutil.h"

//Global swap counter
int swap_ctr;
int compare_ctr;

//namespaces
using namespace std;
using namespace rogueutil;

/******************
 Sorting prototypes
 ******************/
void sort_insertion(vector <int> &v);
void sort_selection(vector <int> &v);
void sort_bubble(vector <int> &v);
void sort_quicksort(vector <int> &v, int L, int R);

/****************************
 Partition function prototype
 ****************************/
int partition(vector <int> &v, int L, int R);


//sort_swap function prototype
void sort_swap(int X, int Y);

//sort_compare function prototype
int sort_compare(int A, int B);

//draw columns function
void col_draw(vector <int> v, int terminal_cols, int terminal_rows);

/***************************************************
                    MAIN FUNCTION
 ***************************************************/
int main() {
    //set main terminal color to white
    setColor(WHITE);

//Find rows and cols of terminal
    int terminal_rows = trows();
    int terminal_cols = tcols();

//vector v
    vector <int> v(terminal_rows - 3);

//randomize seed
    srand(time(NULL));

//populate vector with random values 0-20
    for(int & i : v)
    {
        i = rand() % terminal_cols;
    }

//copy contents into vector copies
    vector <int> v_copy = v;
    vector <int> v_copy_insertion = v;
    vector <int> v_copy_selection = v;
    vector <int> v_copy_bubble = v;
    vector <int> v_copy_quick = v;


//Low and high for partition
    int L = v_copy_quick[0];
    int R = v_copy_quick[terminal_rows - 3];

    cls();
    swap_ctr = 0;
    compare_ctr = 0;
    
    sort_insertion(v_copy_insertion);
    for(int x : v_copy_insertion)
        cout << x << " ";
    cout << endl;
    anykey("Press any key to go:");

    cls();
    swap_ctr = 0;
    compare_ctr = 0;

    sort_selection(v_copy_selection);
    for(int x : v_copy_selection)
        cout << x << " ";
    cout << endl;
    anykey("Press any key to go:");


    cls();
    swap_ctr = 0;
    compare_ctr = 0;

    sort_bubble(v_copy_bubble);
    for(int x : v_copy_bubble) {
        cout << x << " ";
    }
    cout << endl;
    anykey("Press any key to go:");


    cls();
    swap_ctr = 0;
    compare_ctr = 0;

    sort_quicksort(v_copy_quick, L, R);
    for(int x : v_copy_quick)
        cout << x << " ";
    cout << endl;




    return 0;
}


/*******************************************************************
                Sorting functions definitions
 *******************************************************************/
//insertion sort
void sort_insertion(vector <int> &v_copy_insertion)
{
    for(int i = 1; i < v_copy_insertion.size(); i++)
    {
        int j = i;
        while(j > 0 && v_copy_insertion[j] < v_copy_insertion[j - 1])
        {
            sort_compare(v_copy_insertion[j], v_copy_insertion[j - 1]);
            sort_swap(v_copy_insertion[j], v_copy_insertion[j - 1]);
            j--;
        }
    }
    return;
}

//selection sort
void sort_selection(vector <int> &v_copy_selection)
{
    for(int i = 0; i < v_copy_selection.size() - 1; i++)
    {
        int small = i;
        for(int j = i + 1; j < v_copy_selection.size(); j++)
        {
            if(v_copy_selection[j] < v_copy_selection[small])
            {
                small = j;
            }
        }
        sort_compare(v_copy_selection[i], v_copy_selection[small]);
        sort_swap(v_copy_selection[i], v_copy_selection[small]);
    }
    return;
}

//bubble sort
void sort_bubble(vector <int> &v_copy_bubble)
{
    for(int i = 0; i < v_copy_bubble.size() - 1; i++)
    {
        for(int j = 0; j < v_copy_bubble.size() - 1; j++)
        {
            if(v_copy_bubble[j] > v_copy_bubble[j + 1])
            {
                sort_compare(v_copy_bubble[j], v_copy_bubble[j + 1]);
                sort_swap(v_copy_bubble[j], v_copy_bubble[j + 1]);
            }
        }
    }
    return;
}

//quicksort
void sort_quicksort(vector <int> &v_copy_quick, int L, int R)
{
    if(L < R)
    {
        int p = partition(v_copy_quick, L, R);
        sort_quicksort(v_copy_quick, L, p - 1);
        sort_quicksort(v_copy_quick, p, R);
    }
}

//partition function definition
int partition(vector <int> &v_copy_quick, int L, int R)
{
    int result;
    int i = L - 1;
    int j = R + 1;
    int pivot = v_copy_quick[R];
    for(;;)
    {
        while(v_copy_quick[++i] < pivot);
        while(v_copy_quick[--j] > pivot);
        if(i < j)
        {
            sort_compare(v_copy_quick[i], v_copy_quick[j]);
            sort_swap(v_copy_quick[i], v_copy_quick[j]);
        }
        else
        {
            result = i;
            break;
        }
    }
    return result;
}

/****************************************************************
            Sort swap and sort compare definitions
                          Steps 7-10
 ****************************************************************/
//sort_swap function definition
void sort_swap(int X, int Y)
{
    setColor(LIGHTRED);

    swap(X, Y);
    swap_ctr++;
    gotoxy(1, 2);
    cout << "Swaps: " << swap_ctr;
    cout.flush();
    cout << endl;

    setColor(WHITE);
}

//sort_compare function definition
//ignore still working out logic for this
int sort_compare(int A, int B)
{
    setColor(LIGHTGREEN);

    compare_ctr = 0;

    int greater;
    int smaller;
    int equalto;

    if(A - B < 0)
    {
        A = smaller;
    }
    else if(A - B > 0)
    {
        A = greater;
    }
    else
    {
        A = equalto;
    }

    compare_ctr++;
    gotoxy(1, 1);
    cout << "Comparisons: " << compare_ctr;
    cout.flush();

    setColor(WHITE);

    return A;
}

//col_draw function definition
//ignore as well
void col_draw(vector <int> &v_copy, int terminal_cols, int terminal_rows)
{
//if problem with color get rid of setChar('#')
//just use cout << '#';

for(int i = 0; i < terminal_cols; i++)
{
    cout << '#';
}

}

AS stated previously I tried and tested with the C++ swap function and it worked in sorting the copies of the vector v. I am not understanding why my own function sort_swap would not be working due to the fact that the 2nd line of code is using the swap function. Unless I am missing something entirely, I am lost. Thanks for the help

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
erock
  • 13
  • 2
  • 3
    You successfully swap the `X` and `Y` parameters to the function. As far as where those parameters come from, they're not swapped at all. Have you learned about references, in C++? – Sam Varshavchik Mar 23 '23 at 18:23
  • 1
    The `sort_swap` function takes its parameters by value - it has no effect on what the caller passes. – Richard Critten Mar 23 '23 at 18:26
  • @SamVarshavchik I have, but memory is a bit shaky. Would changing to &X and &Y do the trick in function parameters? – erock Mar 23 '23 at 18:27
  • You don't need my permission to try to test your theory... More important: do you ***understand*** what they are how they work, and how they are used? Do you understand that swapping `X` and `Y` accomplishes absolutely nothing, whatsoever? That you need to swap not `X` and `Y`, but what was ***passed*** for those parameters? – Sam Varshavchik Mar 23 '23 at 18:34
  • @RichardCritten Somewhat - I believe that when I am passing the reference to the parameter then changing what happens to the numbers, but I am unsure when and where to use. I should have mentioned that not all work in the code is mine, prof has written code that is to be used, so it is not entirely depicting my knowledge. – erock Mar 23 '23 at 18:35
  • `void sort_swap(int X, int Y)` has two variables `int X` and `int Y` that are **local to that function**. You swap them, and then they are destroyed as you leave that function. Try to understand the _lifetime of a variable_. Understand _when a variable no longer exists_. That is what's tripping you up here. – Drew Dormann Mar 23 '23 at 18:38
  • The TL;DR: Change to `void sort_swap(int &X,int &Y)` For reference, if this where in C, rather than C++, you'd want: `void sort_swap(int *X,int *Y)` and adjust the call to it (e.g): `sort_swap(&v_copy_quick[i], &v_copy_quick[j]);` You may want to try both approaches (which are both valid in C++) to help you understand how references and pointers work/differ. – Craig Estey Mar 23 '23 at 18:48
  • @erock _"... prof has written code that is to be used,..."_ that's useful to know as it lets us answer at the question at correct level. Without knowing that we would be confused as the code shows much more experience than the question would indicate. – Richard Critten Mar 23 '23 at 18:49
  • @SamVarshavchik I tested my theory and after a few comments of explanation, I think I am understanding it a bit better. I'm however receiving an error message now that I frankly don't understand. It is saying I have an undefined reference to my sort_swap functions. I am not sure if this error is occurring because my "theory" is incorrect or something else. – erock Mar 23 '23 at 18:51
  • 1
    It's something else. Most likely: you forgot to update the function's forward declaration. – Sam Varshavchik Mar 23 '23 at 18:52
  • @CraigEstey Thanks for the good explanation. I tried the first switch that you recommended and as I commented just previously am recieving an error that says I have undefined references to my function. However, I dont see any line numbers so i don't know if these errors are in reference to function calls or my function definitions. – erock Mar 23 '23 at 18:53
  • @SamVarshavchik Ahh yes that is correct. Thank you and everyone else who aided me!! – erock Mar 23 '23 at 18:55

1 Answers1

0

Your sort_swap() is simply taking in parameters by value and not by reference. Therefore the values only get copied into the function and then swapped, but without affecting anything outside the method. The solution would be to pass the arguments by reference, like the c++ swap method does it.

void sort_swap(int& X, int& Y){ //by using the "&" parameters get passed by reference and can thus be changed in the method
  setColor(LIGHTRED);

  swap(X, Y);
  swap_ctr++;
  gotoxy(1, 2);
  cout << "Swaps: " << swap_ctr;
  cout.flush();
  cout << endl;

  setColor(WHITE);
}

Of course you must also change your function prototype

Wobby
  • 58
  • 4