Lily's Homework

  • + 0 comments
    def num_of_swaps(arr):
        """Calculates min swaps to sort an array."""
        # Create a dictionary to store the original indices of elements
        ori_idx = {val: i for i, val in enumerate(arr)}
        # Sort the array and store the sorted version
        sorted_arr = sorted(arr)
        swap_num = 0  # Initialize swap counter
    
        # Iterate over the array
        for i in range(len(arr)):
            # If the element is out of place
            if arr[i] != sorted_arr[i]:
                # Find the index of the corresponding element in the original array
                j = ori_idx[sorted_arr[i]]
                # Swap the elements
                arr[i], arr[j] = arr[j], arr[i]
                # Update the indices in the ori_idx dictionary
                ori_idx[arr[i]], ori_idx[arr[j]] = i, j
                swap_num += 1  # Increment swap counter
    
        return swap_num  # Return total swaps
    
    def lilysHomework(arr):
        """Calculates min swaps for ascending/descending sort."""
        # Calculate the minimum number of swaps needed for both ascending and descending orders
        return min(num_of_swaps(arr[:]), num_of_swaps(arr[::-1]))