I want to find the total comparisons for sorting n elements in an array using different sorting algorithms. I don't want to do it manually (in case the number of elements in the array is considerably large). Is there a "formula" to calculate the comparisons for each of the sorting algorithms listed below if for example there is 8 elements in an array containing the following elements [3,24,66,34,8,-5,42,80]? How can I find the comparisons for each?
1) Merge Sort
For example, if I use Merge sort manually in order to find the total numbers of
comparisons for 8 elements, this is what I get:
3, 24, 66, 34, 8, -5, 42, 80
3, 24, 66, 34 8, -5, 42, 80
3, 24 66, 34 8, -5 42, 80
3 24 66 34 8 -5 42 80
3, 24 34, 66 -5, 8 42, 80
3, 24, 34, 66 -5, 8, 42, 80
-5, 3, 8, 24, 34, 42, 66, 80
Total number of comparisons needed to sort this array = 15
I would like to be able to do this using a formula, if possible, not manually.
2) Insertion sort
3<24, 34<66, -5<8, 42<80, step 2:3<34, 24<34, *, -5<42, 8<42, *, step 3:-5<3, 3<8, 8<24, 24<42, 34<42, 42<66, 66<80. In step two, two comparisons that would "theoretically" be there are skipped because of your particular data. So you're right, 15 for this input. Worst case would be 17. Random data is going to often be 15-17, with some using a few less comparisons.