A comparator function is a custom function used in sorting algorithms to determine the order of elements based on specific criteria. By returning a negative, zero, or positive value, it dictates whether one element should appear before, after, or remain in the same position relative to another element in a collection.