Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use merge sort to delete duplicates?

I use recursive merge sort for sorting a link list, but during the merge sort I would like to delete duplicates. Anyone has insight in how to accomplish this?

I am using C code.

like image 750
Degg Avatar asked Dec 08 '22 05:12

Degg


1 Answers

In merge sort you take two (or more) already-sorted lists repeatedly apply the following rules:

  • find the lesser/least of the items of the top of each of the input lists, choosing any of the lowest items if there is a tie
  • remove that item from its list
  • add it to your output list

To remove duplicates, you simply modify the rules very slightly:

  • find the lesser/least of the items of the top of each of the input lists, choosing any of the lowest items if there is a tie
  • remove that item from its list
  • if it is the same as the last item you added to your output list, throw it away
  • otherwise, add it to your output list

This will ensure that no two consecutive items on your output list are the same, and that the items in it are in order, which is what you were after.

like image 98
Tim Avatar answered Dec 17 '22 20:12

Tim