selectionSort FUNCTION NOT WORKIING

Hi there, the function selectionSort in the class below is suppose to perform a selection sort on a list of unsorted integers in the file myFile.txt but it doesn't seem to be working right as it outputs garbage instead of sorting the array list. please assist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef SELECTION_SORT_H
#define SELECTION_SORT_H
#include <fstream>
#include <iostream>
class myList
{
    public:
        myList(int arrayS);
        //myList(const myList& otherList);
        //void operator=(const myList& otherList);
        void selectionSort();
        void print();
    private:
        int arraySize;
        int list[];
        
};
#endif
    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdlib>
#include <iostream>
#include <fstream>
#include "selectionSort.h"

using namespace std;

int main(int argc, char *argv[])
{
    myList listP(11);
    
    listP.selectionSort();
    listP.print();
    
    cout <<endl<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "selectionSort.h"

myList::myList(int arrayS)
{
    arraySize = arrayS;
    list[arrayS];
    
    std::ifstream inFile;
    
    inFile.open("myFile.txt");
    int i = 0;
    while(inFile >> list[i])
        i++;
}

/*myList::myList(const myList& otherList)
{
    for(int index=0; index < otherList.arraySize; index++)
        list[index] = otherList.list[index];
           
}*/

void myList::selectionSort()
{
    int minItem, temp, x;
    
    for(int index=0; index <= arraySize; index++)
    {
        minItem = list[index];
        
        for(int i=index+1; i <= arraySize; i++)
            if(minItem > list[i])
            {
                minItem = list[i];
                x = i;
            }
        
        temp = list[index];
        list[index] = minItem;
        list[x] = temp;
    }
}

void myList::print()
{
    
    for(int i = 0; i < arraySize; i++)
    std::cout << list[i] <<" ";   
}



closed account (o1vk4iN6)
You don't specify the size of your array at line 15.

int list[];
even if I do specify the array size that doesn't fix the problem
You can't use the normal []kind of array if you want to change the size depending on a variable. Use std::vector or use new and delete.
I am not really concerned about changing the size of an array. All I want is to test if the selectionSort() function is working properly that is why I avoided using the dynamic memory array because it requires a copy constructor and an overloaded assignment operator.
Last edited on
Fine, so put a number and respect it. You are stepping out of bounds.
You can't test a single part of your code that relies on other parts of your code if those other parts are not working.
Topic archived. No new replies allowed.