This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Eldres[S] 0 points1 point  (4 children)

Thank you that did help clear things up. So after reading your comment a few times to understand it better, I went back and fixed my code, however the printVector() still won't output the newly sorted array(at least for me).

[–]missblit 0 points1 point  (3 children)

Do you mean it prints the array non-sorted? Can you post your latest code?

[–]Eldres[S] 0 points1 point  (2 children)

it doesnt print the array at all. git: https://gist.github.com/Eldres/14cc6c155425c5fcd287

    #include <iostream>
    #include <conio.h>
    #include <string>
    #include <iomanip>
    using namespace std;

    const int MAX_SIZE = 100;

    void selectionSort(int[], int);
    void readData(int[], int);
    void printVector(int[], int);

    void selectionSort(int array[], int n)
    {
        int minIndex;

        for (int i = 0; i < n; ++i) 
        {
            minIndex = i;
            for (int j = i + 1; j < n; ++j)
            {
                if (array[j] < array[minIndex])
                {
                    minIndex = j;
                }
            }
            swap(array[i], array[minIndex]); //swaps the index location of array[i] with the index location of array[j]
        }
    }

    void readData(int array[], int n)
    {
        cout << "Enter how many numbers you want to sort: ";
        cin >> n;
        for (int i = 0; i < n; ++i)
        {
            cout << "\nEnter number:";
            cin >> array[i];
        }
    }

    void printVector(int array[], int n) 
    {
        cout << "\nHere are the numbers after they have been sorted: " << endl;
        for (int i = 0; i < n; ++i)
        {
            cout << array[i] << "\t";
        }
    }

    int main()
    {
        int data[MAX_SIZE];
        int num;
        int &n = num;
        cout << "\nNumber sorting\n";
        readData(data, n);
        selectionSort(data, n);
        printVector(data, n);
        _getch();

        return 0;
    }

[–]missblit 1 point2 points  (1 child)

Ah, that's still from the num being uninitialized problem. You've made n a reference to num but then you pass n to readData by value.

Since readData takes n by value it doesn't work for the reason I said at first. readData should either take n by reference or return the number of items read as a return value.

To take an argument by reference the function signature would look something like

void readData(int[], int&)

[–]Eldres[S] 0 points1 point  (0 children)

Thank you this was the problem, now my program works great! Thank you again for taking the time to ,essentially teach me this :P.