Heya. I have another case where functions aren't acting like they should. Or at all.
The assignment is to write a program that tests a function that sorts items in ascending order. Code time. As usual, only the code I think is relevant, and I can supply more.
1 2 3 4 5 6 7 8 9 10
|
#include "arraylisttype.h"
#include "searchSortAlgorithm.h"
using namespace std;
template <class elemType>
class unorderedArrayListType : public arrayListType<elemType>, public ssa<elemType> {
public:
void sort();
};
|
I am to create an array object of the class unorderedArrayType, then use sort(); to put them in order.
Now sort() itself is pretty basic:
{ selectionSort(this->list, this->length); }
It would probably help to have selectionSort, it's of the class ssa (stands for search, sort algorithm)
1 2 3 4 5 6 7 8 9 10 11
|
template <class elemType>
void ssa<elemType>::selectionSort(elemType list[], int length)
{
int loc, minIndex;
for (loc = 0; loc < length; loc++)
{
minIndex = minLocation(list, loc, length - 1);
swap(list, loc, minIndex);
}
}
|
minLocation return the smallest element in a sequence
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template <class elemType>
int ssa<elemType>::minLocation(elemType list[], int first, int last)
{
int loc, minIndex;
minIndex = first;
for (loc = first + 1; loc <= last; loc++)
if (list[loc] < list[minIndex])
minIndex = loc;
return minIndex;
}
|
And swap swaps stuff. Give two locations, and this function swaps 'em.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template <class elemType>
int ssa<elemType>::minLocation(elemType list[], int first, int last)
{
int loc, minIndex;
minIndex = first;
for (loc = first + 1; loc <= last; loc++)
if (list[loc] < list[minIndex])
minIndex = loc;
return minIndex;
}
|
And as for main
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
|
int main()
{
unorderedArrayListType<int> unorder(10);
int intList[] = {2, 48, 14, 5, 53,
56, 69, 70, 35, 16};
print(intList, 10);
unorder.sort();
print(intList, 10);
system("PAUSE");
return 0;
}
template <class elemType>
void print(elemType list[], int length)
{
for (int i = 0; i < length; i++)
cout << list[i] << " ";
cout << endl;
}
|
The first call to print(intList, 10) is supposed to print the items in the array in the order they were given, which it does. Then sort is supposed to sort them in ascending order. The second print is supposed to print them in this order. It instead prints the unsorted list.
So... anybody know why sort isn't sorting?
Thanks for reading!