📌  相关文章
📜  如果N≤2 | X – Y |,则通过在位置X和Y交换元素来排序前N个自然数的排列。

📅  最后修改于: 2021-04-27 21:43:30             🧑  作者: Mango

给定一个由前N个自然数组成的数组arr [] ( N为偶数),任务是找到一个交换序列,该序列可以通过交换位置XY处的元素对数组进行排序,如果
N≤2 | X – Y |
注意:考虑基于1的索引

例子:

方法:解决此问题的想法是使用数组position []来保持数组arr []中元素的位置,并 执行arr [x]和arr [y]以及position [arr [x]]position [arr [y]]的交换请按照以下步骤解决问题:

  • 初始化数组newArr []以直接按位置引用元素。
  • 初始化向量位置以存储原始数组元素的位置,并初始化向量答案以存储执行的交换。
  • 从i = 1遍历到N,并检查以下条件:
    • 如果position [i] = i:继续到下一个整数,因为该整数已经在其正确位置。
    • 如果| position [i] – i | > = N / 2 :调用perform_swap(i,position [i])
    • 否则:保留变量initial_position,以保持整数i的当前位置,即position [i]
      • 如果| position [i] -1 | > = N / 2:调用perform_swap(position [i],1)
        • 如果| i-1 | > = N / 2:调用perform_swap(i,1)perform_swap(initial_position,1)
        • 否则:调用perform_swap(1,N)perform_swap(N,i)perform_swap(1,initial_position)
      • 否则:调用perform_swap(position [i],N)perform_swap(N,i)

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
#include 
#include 
using namespace std;
 
// Function to swap values in arr and position
void perform_swap(vector& arr, vector& position,
                  vector >& answer, int x,
                  int y)
{
 
    // Swap position[arr[x]] and position[arr[y]]
    swap(position[arr[x]], position[arr[y]]);
 
    // Swap arr[x] and arr[y]
    swap(arr[x], arr[y]);
 
    // Push x and y to the answer vector
    answer.push_back({ x, y });
}
 
// Function to find the sequence of swaps
// that can sort the array
void sortBySwap(int N, int arr[])
{
 
    // Shifted vector of Array arr
    vector newArr(N + 1, 0);
 
    for (int i = 0; i < N; i++)
        newArr[i + 1] = arr[i];
 
    // Keep an vector to maintain positions
    vector position(N + 1, 0);
 
    // Vector to maintain the swaps performed
    vector > answer;
 
    // Assign position of elements in position array
    for (int i = 1; i <= N; i++)
        position[newArr[i]] = i;
 
    // Traverse from 1 to N
    for (int i = 1; i <= N; i++) {
 
        // If element is already at it's right position
        if (i == position[i])
            continue;
 
        // If current and right place can be directly
        // swapped
        if (abs(i - position[i]) >= N / 2) {
            perform_swap(newArr, position, answer, i,
                         position[i]);
        }
        else {
 
            // Initial position of integer i
            int initial_position = position[i];
 
            // If |position[i]-1| >= N/2 :
            // Call perform_swap(position[i], 1)
            if (abs(position[i] - 1) >= N / 2) {
                perform_swap(newArr, position, answer,
                             position[i], 1);
 
                // If |i-1| >= N/2 : Call perform_swap(i, 1)
                // and perform_swap(initial_position, 1)
                if (abs(i - 1) >= N / 2) {
                    perform_swap(newArr, position, answer,
                                 i, 1);
                    perform_swap(newArr, position, answer,
                                 initial_position, 1);
                }
 
                // Otherwise: Call perform_swap(1, N),
                // perform_swap(N, i) and
                // perform_swap(1, initial_position).
                else {
                    perform_swap(newArr, position, answer,
                                 1, N);
                    perform_swap(newArr, position, answer,
                                 N, i);
                    perform_swap(newArr, position, answer,
                                 1, initial_position);
                }
            }
 
            // Otherwise: Call perform_swap(position[i], N)
            // and perform_swap(N, i);
            else {
                perform_swap(newArr, position, answer,
                             position[i], N);
                perform_swap(newArr, position, answer, N,
                             i);
            }
        }
    }
 
    // Print the sequences which sorts
    // the given array
    for (int i = 0; i < (int)answer.size(); i++)
        printf("%d %d\n", answer[i].first,
               answer[i].second);
}
 
// Driver Code
int main()
{
    // Input Array
    int arr[] = { 3, 4, 1, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    sortBySwap(N, arr);
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class Pair
{
    int first, second;
     
    Pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
class GFG{
 
static void swap(int[] a, int i, int j)
{
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}
 
// Function to swap values in arr and position
static void perform_swap(int[] arr, int[] position,
                         List answer, int x,
                         int y)
{
     
    // Swap position[arr[x]] and position[arr[y]]
    swap(position, arr[x], arr[y]);
 
    // Swap arr[x] and arr[y]
    swap(arr, x, y);
 
    // Push x and y to the answer vector
    answer.add(new Pair(x, y));
}
 
// Function to find the sequence of swaps
// that can sort the array
static void sortBySwap(int N, int arr[])
{
     
    // Shifted vector of Array arr
    int[] newArr = new int[N + 1];
 
    for(int i = 0; i < N; i++)
        newArr[i + 1] = arr[i];
 
    // Keep an vector to maintain positions
    int[] position = new int[N + 1];
 
    // Vector to maintain the swaps performed
    @SuppressWarnings("unchecked")
    List answer = new ArrayList();
 
    // Assign position of elements in position array
    for(int i = 1; i <= N; i++)
        position[newArr[i]] = i;
 
    // Traverse from 1 to N
    for(int i = 1; i <= N; i++)
    {
         
        // If element is already at it's
        // right position
        if (i == position[i])
            continue;
 
        // If current and right place can
        // be directly swapped
        if (Math.abs(i - position[i]) >= N / 2)
        {
            perform_swap(newArr, position, answer, i,
                         position[i]);
        }
        else
        {
             
            // Initial position of integer i
            int initial_position = position[i];
 
            // If |position[i]-1| >= N/2 :
            // Call perform_swap(position[i], 1)
            if (Math.abs(position[i] - 1) >= N / 2)
            {
                perform_swap(newArr, position, answer,
                             position[i], 1);
 
                // If |i-1| >= N/2 : Call
                // perform_swap(i, 1) and
                // perform_swap(initial_position, 1)
                if (Math.abs(i - 1) >= N / 2)
                {
                    perform_swap(newArr, position,
                                 answer, i, 1);
                    perform_swap(newArr, position,
                                 answer,
                                 initial_position, 1);
                }
 
                // Otherwise: Call perform_swap(1, N),
                // perform_swap(N, i) and
                // perform_swap(1, initial_position).
                else
                {
                    perform_swap(newArr, position,
                                 answer, 1, N);
                    perform_swap(newArr, position,
                                 answer, N, i);
                    perform_swap(newArr, position,
                                 answer, 1,
                                 initial_position);
                }
            }
 
            // Otherwise: Call perform_swap(position[i],
            // N) and perform_swap(N, i);
            else
            {
                perform_swap(newArr, position, answer,
                             position[i], N);
                perform_swap(newArr, position, answer,
                             N, i);
            }
        }
    }
 
    // Print the sequences which sorts
    // the given array
    for(int i = 0; i < answer.size(); i++)
        System.out.println(answer.get(i).first + " " +
                           answer.get(i).second);
}
 
// Driver code
public static void main(String[] args)
{
     
    // Input Array
    int arr[] = { 3, 4, 1, 2 };
    int N = arr.length;
 
    // Function Call
    sortBySwap(N, arr);
}
}
 
// This code is contributed by jithin


Python3
# Python3 program for the above approach
 
# Function to swap values in arr and position
def perform_swap(x, y):
    global arr, position, answer
 
    # Swap position[arr[x]] and position[arr[y]]
    position[arr[x - 1]], position[arr[y - 1]] = position[arr[y - 1]], position[arr[x - 1]]
    arr[x - 1], arr[y - 1] = arr[y - 1], arr[x - 1]
 
    # Push x and y to the answer vector
    answer.append([x, y])
 
# Function to find the sequence of swaps
# that can sort the array
def sortBySwap(N, arr):
    global newArr, position, answer
 
    for i in range(N):
        newArr[i + 1] = arr[i]
 
    # Assign position of elements in position array
    for i in range(1, N + 1):
        position[newArr[i]] = i
 
    # Traverse from 1 to N
    for i in range(N + 1):
 
        # If element is already at it's right position
        if (i == position[i]):
            continue
 
        # If current and right place can be directly
        # swapped
        if (abs(i - position[i]) >= N // 2):
            perform_swap(i, position[i])
        else:
            # Initial position of integer i
            initial_position = position[i]
 
            # If |position[i]-1| >= N/2 :
            # Call perform_swap(position[i], 1)
            if (abs(position[i] - 1) >= N // 2):
                perform_swap(position[i], 1)
 
                # If |i-1| >= N/2 : Call perform_swap(i, 1)
                # and perform_swap(initial_position, 1)
                if (abs(i - 1) >= N // 2):
                    perform_swap(i, 1)
                    perform_swap(initial_position, 1)
 
                # Otherwise: Call perform_swap(1, N),
                # perform_swap(N, i) and
                # perform_swap(1, initial_position).
                else:
                    perform_swap(1, N)
                    perform_swap(N, i)
                    perform_swap(1, initial_position)
 
            # Otherwise: Call perform_swap(position[i], N)
            # and perform_swap(N, i)
            else:
                perform_swap(position[i], N)
                perform_swap(N, i)
 
    # Prthe sequences which sorts
    # the given array
    for i in answer:
        print(i[0], i[1])
 
# Driver Code
if __name__ == '__main__':
   
    # Input Array
    arr = [3, 4, 1, 2]
    N = len(arr)
 
    newArr = [0 for i in range(N+1)]
    position = [i for i in range(N+1)]
 
    answer = []
 
    # Function Call
    sortBySwap(N, arr)
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class Pair
{
  public int first, second;
 
  public Pair(int first, int second)
  {
    this.first = first;
    this.second = second;
  }
}
public class GFG
{
  static void swap(int[] a, int i, int j)
  {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
  }
 
  // Function to swap values in arr and position
  static void perform_swap(int[] arr, int[] position,
                           List answer, int x,
                           int y)
  {
     
    // Swap position[arr[x]] and position[arr[y]]
    swap(position, arr[x], arr[y]);
 
    // Swap arr[x] and arr[y]
    swap(arr, x, y);
 
    // Push x and y to the answer vector
    answer.Add(new Pair(x, y));
  }
 
  // Function to find the sequence of swaps
  // that can sort the array
  static void sortBySwap(int N, int[] arr)
  {
 
    // Shifted vector of Array arr
    int[] newArr = new int[N + 1];
 
    for(int i = 0; i < N; i++)
      newArr[i + 1] = arr[i];
 
    // Keep an vector to maintain positions
    int[] position = new int[N + 1];
 
    // Vector to maintain the swaps performed
 
    List answer = new List();
 
    // Assign position of elements in position array
    for(int i = 1; i <= N; i++)
      position[newArr[i]] = i;
 
    // Traverse from 1 to N
    for(int i = 1; i <= N; i++)
    {
 
      // If element is already at it's
      // right position
      if (i == position[i])
        continue;
 
      // If current and right place can
      // be directly swapped
      if (Math.Abs(i - position[i]) >= N / 2)
      {
        perform_swap(newArr, position, answer, i,
                     position[i]);
      }
      else
      {
 
        // Initial position of integer i
        int initial_position = position[i];
 
        // If |position[i]-1| >= N/2 :
        // Call perform_swap(position[i], 1)
        if (Math.Abs(position[i] - 1) >= N / 2)
        {
          perform_swap(newArr, position, answer,
                       position[i], 1);
 
          // If |i-1| >= N/2 : Call
          // perform_swap(i, 1) and
          // perform_swap(initial_position, 1)
          if (Math.Abs(i - 1) >= N / 2)
          {
            perform_swap(newArr, position,
                         answer, i, 1);
            perform_swap(newArr, position,
                         answer,
                         initial_position, 1);
          }
 
          // Otherwise: Call perform_swap(1, N),
          // perform_swap(N, i) and
          // perform_swap(1, initial_position).
          else
          {
            perform_swap(newArr, position,
                         answer, 1, N);
            perform_swap(newArr, position,
                         answer, N, i);
            perform_swap(newArr, position,
                         answer, 1,
                         initial_position);
          }
        }
 
        // Otherwise: Call perform_swap(position[i],
        // N) and perform_swap(N, i);
        else
        {
          perform_swap(newArr, position, answer,
                       position[i], N);
          perform_swap(newArr, position, answer,
                       N, i);
        }
      }
    }
 
    // Print the sequences which sorts
    // the given array
    for(int i = 0; i < answer.Count; i++)
      Console.WriteLine(answer[i].first + " " +
                        answer[i].second);
  }
 
  // Driver code
  static public void Main ()
  {
 
    // Input Array
    int[] arr = { 3, 4, 1, 2 };
    int N = arr.Length;
 
    // Function Call
    sortBySwap(N, arr);
  }
}
 
// This code is contributed by avanitrachhadiya2155


输出:
1 3
2 4

时间复杂度: O(N)
辅助空间: O(1)