calculate total no of comparision using selection sort?

kindly tell me where and how to put comparision condition in order to caculate total number of comparision in selection sort
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
 static void selectsort(int[] data, int n)
        {
            int i, j;
             

            for (i = 0; i < n; i++)
            {
                
                int min = i;
                for (j = i + 1; j < n; j++)

            


                    if (data[j] < data[min])
                        
                        min = j; //find min value
                //then swap it with the beginning item of the unsorted list
                int temp = data[i];
                data[i] = data[min];
                data[min] = temp;
               
            }

        }



    }
}

You have comparsion on line 15. This is only one. You just need some kind of counter to store amount and increment it every time this line is executed.

One way to do
1) make function return int so we can get access to count of comparsions.
2) add int comp = 0; at the very begining of your function.
3) Change line 15 to: if (++comp, data[j] < data[min])
4) add return comp; at the very end of your function
Topic archived. No new replies allowed.