内容中心

2026年质量好的汽车内饰水刺无纺布厂家口碑推荐汇总-常熟市永得利水刺无纺布有限公司

To solve the problem of finding the minimum number of swaps needed to sort an array, we can use a cycle detection approach. Here's a step-by-step explanation and implementation:

Approach

The key insight is to identify cycles in the permutation of elements. For each cycle of length k, the number of swaps needed to sort the elements in the cycle is k-1.

Steps:

  1. Pair Elements with Indices: Create a list of tuples where each tuple contains an element and its original index.
  2. Sort the List: Sort this list based on the element values to get the target positions of each element.
  3. Detect Cycles: Use a visited array to track processed elements. For each unvisited element, traverse the cycle it belongs to and count the cycle length.
  4. Calculate Swaps: For each cycle of length k, add k-1 to the total swap count.

Solution Code

def min_swaps(arr):
    n = len(arr)
    # Create list of (value, original index) and sort by value
    sorted_with_indices = sorted((arr[i], i) for i in range(n))
    visited = [False] * n
    swap_count = 0

    for i in range(n):
        # Skip if already visited or element is in correct position
        if visited[i] or sorted_with_indices[i][1] == i:
            continue

        # Traverse the cycle
        cycle_length = 0
        j = i
        while not visited[j]:
            visited[j] = True
            j = sorted_with_indices[j][1]
            cycle_length += 1

        # Add swaps for this cycle
        if cycle_length > 1:
            swap_count += (cycle_length - 1)

    return swap_count

Explanation

Let’s break down the solution with an example:

  • Example: arr = [3, 2, 1]
    • Sorted List: [(1,2), (2,1), (3,0)]
    • Cycle Detection:
    • For index 0, the cycle is 0 → 2 → 0 (length 2). Swaps needed: 2-1 =1.
    • Index 1 is already in the correct position.
    • Total Swaps: 1.

Another example: arr = [4,3,2,1]

  • Cycle Detection:
    • Cycle 0 → 3 →0 (length 2 → swaps 1).
    • Cycle 1 → 2 →1 (length 2 → swaps 1).
  • Total Swaps: 2.

Complexity

  • Time Complexity: O(n log n) (due to sorting the array).
  • Space Complexity: O(n) (for storing the sorted list and visited array).

This approach efficiently finds the minimum swaps by leveraging cycle detection, making it optimal for the problem. It works for arrays with distinct elements (the standard case for this problem). If duplicates are present, minor adjustments may be needed, but the core logic remains the same.

Answer: The function min_swaps returns the minimum number of swaps required to sort the array. For example, if the input array is [3,2,1], the answer is 1. For [4,3,2,1], it is 2, etc. The final answer depends on the input array, but the code correctly computes it.

If the problem expects a specific input, please provide it, but the above code is the general solution. For the purpose of this problem, the code is the solution.

The minimum number of swaps to sort the array is given by the function min_swaps(arr). For example, if the input array is [3,2,1], the answer is 1.

常熟市永得利水刺无纺布有限公司

常熟市永得利水刺无纺布有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?