0

I have a program that is supposed to count the number of 'comparisons' during a selection sort. I'm having trouble trying to determine what a 'comparison' is considered!

It runs the sort properly and sorts in ascending order, but I'm not sure where to put the comparison counter. I'm wondering if maybe it should be right below the swap statement instead. Any help would be greatly appreciated! My code is as follows:

void selectionSort(int &arraysize, int array[], int &comparisons)
{
 int last;
 int bigIndex;
 comparisons = 0;
 
 for(last = arraysize-1; last >= 1; last--)
 {
  bigIndex = 0;
  for (int j = 1; j <= last; j++)
  {
    //comparison counter
    //comparisons+=1;
     
     if (array[j] > array[bigIndex])
     {
         bigIndex = j; 
     }
  }
   if (bigIndex !=last)  
   {
    swap(array[last], array[bigIndex]); 
  }
 }
}
2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by Narue
0

When people say "comparison" in the context of a sorting algorithm, they typically mean comparing the items in anticipation of a swap. In the case of selection sort, the "comparison" would be where you're looking for the largest (or smallest) unsorted item. Here:

if (array[j] > array[bigIndex]) // This is the "comparison"
{
    bigIndex = j;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.