You are viewing a single comment's thread. Return to all comments →
def lilysHomework(arr): elements = [(value, index) for index, value in enumerate(arr)] sorted_elements = sorted(elements) index_map = {index: i for i, (_, index) in enumerate(sorted_elements)} asc_swaps = calculate_swaps(arr, index_map) sorted_elements = sorted(elements, reverse=True) index_map = {index: i for i, (_, index) in enumerate(sorted_elements)} desc_swaps = calculate_swaps(arr, index_map) return min(asc_swaps, desc_swaps) def calculate_swaps(arr, index_map): swaps = 0 visited = [False] * len(arr) for i in range(len(arr)): if visited[i] or index_map[i] == i: continue cycle_size = 0 j = i while not visited[j]: visited[j] = True j = index_map[j] cycle_size += 1 if cycle_size > 0: swaps += cycle_size - 1 return swaps
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →