Search code examples
c++stringsortingvectorselection-sort

Bug in selection sort loop


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

Solution

  • vectorRange defined but not used.