Lily's Homework

  • + 0 comments

    Sort the Array Track Cycles Count Swaps = (cycle length - 1) I run the test array [3,4,2,5,1] ->output 4, but the expected answer is 2,why?

    def lilysHomework(arr): # Write your code here # Create a list of tuples where each tuple is (element, original_index) n = len(arr) arr_with_indices = [(arr[i], i) for i in range(n)]

    # Sort the array by the element values
    arr_with_indices.sort(key=lambda x: x[0])
    
    # To track visited elements
    visited = [False] * n
    swaps = 0
    
    for i in range(n):
        # If the element is already visited or already in the correct position, skip it
        if visited[i] or arr_with_indices[i][1] == i:
            continue
    
        # Start a new cycle
        cycle_size = 0
        j = i
        while not visited[j]:
            visited[j] = True
            j = arr_with_indices[j][1]  # Move to the next element in the cycle
            cycle_size += 1
    
        # If there is a cycle of size `k`, it takes `k - 1` swaps to sort the cycle
        if cycle_size > 1:
            swaps += cycle_size - 1
    
    return swaps