sircrisp
sircrisp

Reputation: 1067

Bubblesort giving access violation

Hi everyone I am trying to finish a assignment for class where I need to sort a File full of employees by their ID number. There are 10 lines in the file each with an employees info. The order is ID LASTNAME FIRSTNAME

The program ran fine before I wrote the sort function and copied all the data properly into the array, but now after adding my sort function I keep getting a access violation with no hints as to what is causing it.

I would appreciate any help.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class Employee
{
public:
    int _id;
    string _lastName;
    string _firstName;

    Employee()
    {
        _id = 0;
        _lastName = "n/a";
        _firstName = "n/a";
    }
};

void copyFile10(Employee [], int);
void sortFile10(Employee [], int);
int main()
{
    const int size10 = 10;
    Employee employees10[size10];

    copyFile10(employees10, size10); //1.fill array/copy file
    sortFile10(employees10, size10); //2. sort

    system("pause");
    return 0;
}

void copyFile10(Employee employees10[], const int size)
{
    ifstream data10("data_10.dat");
    for(int count = 0; count < 10; count++) //1.fill array/copy file
    {
        data10 >> employees10[count]._id;
        data10 >> employees10[count]._lastName;
        data10 >> employees10[count]._firstName;
    }
    data10.close();
}

void sortFile10(Employee employees10[], const int size)
{
    Employee buff1;
    Employee buff2;
    int counter = 0;
    bool ordered = false;

    while (ordered == false)
    {
        for(int count = 0; count < size-1; count++)
        {
            if(employees10[count]._id > employees10[count+1]._id)
            {
                buff1._id = employees10[count+1]._id;
                buff1._lastName = employees10[count+1]._lastName;
                buff1._firstName = employees10[count+1]._firstName;

                buff2._id = employees10[count]._id;
                buff2._lastName = employees10[count]._lastName;
                buff2._firstName = employees10[count]._firstName;

                employees10[count]._id = buff1._id;
                employees10[count]._lastName = buff1._lastName;
                employees10[count]._firstName = buff1._firstName;

                employees10[count+1]._id = buff2._id;
                employees10[count+1]._lastName = buff2._lastName;
                employees10[count+1]._lastName = buff2._lastName;

                counter++;
            }
            if(counter == 0)
            ordered = true;
            else
                counter = 0;
        }
    }
}

Upvotes: 0

Views: 148

Answers (1)

Pete Becker
Pete Becker

Reputation: 76370

for(int count = 0; count < size; count++)
        {
            if(employees10[count]._id > employees10[count+1]._id)

What happens here on the last iteration of the loop (i.e. when count is 9)?

Upvotes: 1

Related Questions