How can I pair socks from a pile efficiently?

后端 未结 30 1208
旧巷少年郎
旧巷少年郎 2020-11-27 08:37

Yesterday I was pairing the socks from the clean laundry and figured out the way I was doing it is not very efficient. I was doing a naive search — picking one sock and

30条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 09:15

    Case 1: All socks are identical (this is what I do in real life by the way).

    Pick any two of them to make a pair. Constant time.

    Case 2: There are a constant number of combinations (ownership, color, size, texture, etc.).

    Use radix sort. This is only linear time since comparison is not required.

    Case 3: The number of combinations is not known in advance (general case).

    We have to do comparison to check whether two socks come in pair. Pick one of the O(n log n) comparison-based sorting algorithms.

    However in real life when the number of socks is relatively small (constant), these theoretically optimal algorithms wouldn't work well. It might take even more time than sequential search, which theoretically requires quadratic time.

提交回复
热议问题