I have to keep track of all comparisons in this selection sort, but when I do only 1 is returned for the value out of a list of 1000. I am not sure I implemented it correctly but I am sure I placed the comparison count correctly/. Typically a selection sort has a fixed amount of key comparisons but our instructor has forbidden the use of formulas to track them. I am curious why this output keeps returning:
comp = 1
swap = 1
template <class elemType>
void selectionSort(elemType list[], int length)
{
int loc, minIndex;
int first;
int last, second;
int swaps =0;
int comp = 0;
minIndex = first;
for (loc = 0; loc < length; loc++)
{
comp+=1;
for(loc = first +1; loc<=last; loc++)
{
comp+=1;
if(list[loc]<list[minIndex])
minIndex=loc;
comp+=1;
}
elemType temp;
temp= list[first];
list[first]= list[second];
list[second] = temp;
swaps+=1;
}
// comp = (length *(length-1)/2);
cout<<"swaps= "<<swaps<<endl;
cout<<"comps= "<<comp<< endl;
}
Any thoughts are appreciated
I guess your sorting itself is not working. You need to properly initialize
last,firstandsecondvariables (specially thelast) and then move(increment) them.Since your
lastvariable is defaulted with0, its not performing the iterations because ofloc<=lastcondition in the second for loop as you have desired. I think you need to initialize it as :There is one more issue: In both the loops, you are using the same index variable i.e.
loc. I think you need to use two different variables.Once you fix the logic so that it performs the full sorting, you will get the right count.