Question

I need to make a program that will accept a input file of numbers(integer.txt) which will be sorted one number per line, into a vector, then use a selection sort algorithm to sort the numbers in descending order and write them to the output file (sorted.txt). I'm quite sure something is wrong in my selectionSort() function that is causing the loop not to get the right values, because after tested with cout I get vastly improper output. I'm sure it's a beginning programmer's goof.

vector<string> getNumbers()
{
vector<string> numberList;
ifstream inputFile ("integer.txt");
string pushToVector;
while (inputFile >> pushToVector)
    {
    numberList.push_back(pushToVector);
    }
return numberList;
}



vector<string> selectionSort()
{
vector<string> showNumbers = getNumbers();
int vectorMax = showNumbers.size();
int vectorRange = (showNumbers.size() - 1);
int i, j, iMin;
for (j = 0; j < vectorMax; j++)
    {
    iMin = j;
    for( i = j; i < vectorMax; i++)
        {
        if(showNumbers[i] < showNumbers[iMin])
            {
            iMin = i;
            }
        }
    if (iMin != j)
        {
        showNumbers[j] = showNumbers [iMin];
        }
    }
return showNumbers;
}

void vectorToFile()
{
vector<string> sortedVector = selectionSort();

int vectorSize = sortedVector.size();
ofstream writeTo;
writeTo.open("sorted.txt");
int i = 0;
while (writeTo.is_open())
    {
    while (i < vectorSize)
        {
        writeTo << sortedVector[i] << endl;
        i += 1;
        }
    writeTo.close();
    }
return;
}

int main()
    {
    vectorToFile();
    }
Was it helpful?

Solution

vectorRange defined but not used.

OTHER TIPS

In your selectionSort(), the only command that changes the vector is:

showNumbers[j] = showNumbers [iMin];

Every time control reaches that line, you overwrite an element of the vector.

You must learn to swap two values, before you even think about sorting a vector.

Also, your functions are over-coupled. If all you want to fix is selectionSort, then you should be able to post that plus a main that calls it with some test data and displays the result, but no, your functions all call each other. Learn to decouple.

Also your variable names are awful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top