Pascal - sorting - numer of comparisions and changes lazarus / 61-Beginners ---------------------------------------------------------------------- yumi382 · 2021-01-17 12:55 Hi! I need some help with sorting... I have an array that has to be sorted in different ways (Bubble sort, Insertion sort, Quick Sort etc). Everything is already done.. but I have to implement a code (in that sorting procedure) that counts the number of comparisons and changes of the array elements. I have no idea how to do it... I was thinking about doing it with a random variable that is incremented but it doesn't really work. I always get the same number which is 20. Is there anyone who could help me or give a hint? Thanks a lot! ---------------------------------------------------------------------- wp · 2021-01-17 13:29 If you don't have it already write a Compare function which is called instead of direct comparison, i.e. instead of "if data[ i] > data[j]" call "if Compare(data[ i], data[j]) > 0". The compare function gets the two values to be compared as parameters, and it must return a positive number if the first parameter is larger than the second one. For numbers this can easily be achieved by calculating the difference, for strings use the StrCompare function in unit SysUtils. Call the Compare function from each sorting algorithm. With the Compare function you have a unique point where you can increment a global "CompareCounter" variable. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  CompareCounter: Integer; function Compare(a, b: Integer): Integer;begin  Result := a - b;  inc(CompareCounter);end; Of course you must reset the CompareCounter before you begin the sort. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   Comparecounter := 0;  BubbleSort([3, 6, 1, 2]);  WriteLn(CompareCounter, ' comparisons');