How do I sort this printed vector without C++ library sort function?

After learning how to print a vector from an input file of numbers, I am now trying to learn how to sort those numbers using an algorithm and not the sort(arr.begin(), arr.end()) function. This is my sort algorithm:

for (i = 0; i < n-1; i++)
    for (j = i+1; j < n; j++)
        if (arr[i] > arr[j])
            swap(arr[i], arr[j]);

And my code:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;


int main()
{
    vector<int> arr;

    ifstream infile;
    infile.open("numbers.txt");

    if (infile.fail())
    {
        cout << "Could not open file numbers." << "\n";
        return 1;
    }

    int i;
    int j;
    int n;
    int data;
    infile >> data;
    while (!infile.eof())
    {
        arr.push_back(data);
        infile >> data;
    }

    for (i = 0; i < n-1; i++)
        for (j = i+1; j < n; j++)
            if (arr[i] > arr[j])
                swap(arr[i], arr[j]);

    for (unsigned i = 0; i < arr.size(); ++i) 
    {
        cout << arr[i] << " " << endl;
    }

}

Using this input file:

20
10
5
15
35
40
25
30

I believe my issue has to do with how i, n, & j are declared but cannot figure out anything past that. I hope the information provided is sufficient. I am VERY new to this. Thank you.

Answers


You forgot to initialize and increase (or set) the value of n.

Use

int n = 0;
while (!infile.eof()) {
  arr.push_back(data);
  infile >> data;
  n++;
}

or

int n = 0;
while (!infile.eof()) {
  arr.push_back(data);
  infile >> data;
}
n = arr.size();

I don't know how much you understand about sorting algorithms but this might be valuable: http://sorting.at/


Once n initialized to arr.size(), it works : (https://ideone.com/aNCwN6).


Need Your Help

How do I change master page for a specific page in sharepoint

sharepoint-2007 master-pages

How can I apply a different master page for two pages within a SharePoint site?

git stderr output can't pipe

git bash pipe named-pipes zenity

I'm writing a graphical URI handler for git:// links with bash and zenity, and I'm using a zenity 'text-info' dialog to show git's clone output while it's running, using FIFO piping. The script is ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.