I’m working with a custom object that needs sorting but it’s not a standard list
type. The object has indexed elements with sortable values and provides a swap
method for element exchange.
Instead of the typical element swapping pattern:
data[x], data[y] = data[y], data[x]
I need to use the object’s swap method. I want to leverage Python’s built-in sorting rather than implementing my own algorithm.
I tried creating a wrapper approach with bubble sort:
def bubble_sort_with_swap(arr, start, finish):
pivot_point = start
for index in range(start + 1, finish + 1):
if arr[index] <= arr[start]:
pivot_point += 1
arr.exchange(index, pivot_point)
arr.exchange(pivot_point, start)
return pivot_point
def sort_recursive(arr, start=0, finish=None):
if finish is None:
finish = len(arr) - 1
def _sort_helper(arr, start, finish):
if start >= finish:
return
pivot = bubble_sort_with_swap(arr, start, finish)
_sort_helper(arr, start, pivot - 1)
_sort_helper(arr, pivot + 1, finish)
return _sort_helper(arr, start, finish)
class CustomSwapper(list):
def __init__(self, data, target_obj):
super().__init__(data)
self._target = target_obj
def exchange(self, pos1, pos2):
if pos1 == pos2:
return
self[pos1], self[pos2] = self[pos2], self[pos1]
self._target.exchange(pos1, pos2)
wrapper = CustomSwapper(my_data, my_object)
sort_recursive(wrapper)
Is there a way to make Python’s built-in sort work with custom swap operations, or should I stick with custom sorting implementations?