2

I started on cs502020 new pset3 -tideman few days ago and haven't been able to figure out how to implement sort_pairs, where one has to sort the struct in an array based on strength of the victory. Can anyone help explain how to implement it? The walkthrough doesn't really explain the process. The specification is here: https://cs50.harvard.edu/x/2020/psets/3/tideman/

Best Regards, Jun

-2

You want to sort the pairs based on the preferences for this winner/loser combination. The ones with the largest preference should come first.

Pick any sorting algorithm (week 3 has quite a collection of those, week 3's website has four shorts directly related), and implement it, comparing based on this preference instead of a simple a < b. Pick any algorithm that you understand, or maybe use qsort from stdlib.h (likely implements the quick sort algorithm, though it is not required to, time complexity might be O(n²), using that one might not be expected for somebody in week 3 even if more comfortable).

edit: In the position where you would compare two array elements a and b, you would instead compare preferences[a.winner][a.loser] and preferences[b.winner][b.loser]. To change ascending to descending, one would swap < and >.

| improve this answer | |
  • My main problem is I don't understand how to sort based on the frequency of winner/loser combination? I can see how through simple a < b sort based on which number is bigger. – junyuanjyjy Jan 5 at 7:46
  • In this case, a and b are not numbers, but pairs, and the metric would be something like preferences[a.winner][a.loser] < preferences[b.winner][b.loser] (comparison operator depends on where it is used, swapping < and > would invert the order). – Blauelf Jan 5 at 11:04
  • @Blauelf your solution worked fine thanks but i need more illustration about why my code did not work i created a variable (pairs.strength) and set it to be equal preferences[pairs.winner][pairs.loser] i used this pair.strength in my comparison i wondered why it didnt work although it is almost the same thing – Mohamed Diaa Mar 27 at 6:54
  • I don't know your code, so how would I know what's wrong? Do you perform your element comparison based on the preferences, as required by the problem specification? – Blauelf Mar 27 at 6:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .