📌  相关文章
📜  检查数组是否可以通过交换相邻元素进行排序,使得每个元素交换偶数次

📅  最后修改于: 2022-05-13 01:56:06.512000             🧑  作者: Mango

检查数组是否可以通过交换相邻元素进行排序,使得每个元素交换偶数次

给定一个由N个整数组成的数组arr[] ,任务是检查数组是否可以通过交换相邻元素任意次数来排序,使得每个数组元素甚至交换多次。

例子:

方法:给定的问题可以通过观察两个相邻的偶数或奇数索引元素可以交换的事实来解决,因为在不改变中间元素的情况下对交换的次数没有限制。因此,想法是在各自的偶数和奇数索引处重新排列数组元素,并检查形成的数组是否已排序。请按照以下步骤解决给定的问题:

  • 将所有数组元素arr[i]存储在另一个数组中的奇数索引处,例如odd[]
  • 将所有数组元素arr[i]存储在另一个数组中的偶数索引处even[]
  • 以升序对数组odd[]even[]进行排序。
  • 初始化两个变量,比如jk0 ,用于遍历数组odd[]even[]
  • 使用变量i迭代范围[0, N]并执行以下步骤:
    • 如果i的值为奇数,则将元素odd[j]压入数组res[]并将j的值增加1
    • 如果i的值是偶数,则将元素even[k]压入数组res[]并将j的值增加1
  • 完成上述步骤后,如果数组res[]已排序,则打印Yes 。否则,打印No

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to check if the array can be
// made sorted by adjacent swapping of
// element such that each array element
// is swapped even number of times
bool isSorted(int arr[], int n)
{
    vector evenArr, oddArr;
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // Stores all the even positions
        // elements
        if (i % 2 == 0)
            evenArr.push_back(arr[i]);
 
        // Stores all the odd positions
        // elements
        else
            oddArr.push_back(arr[i]);
    }
 
    // Sort the array evenArr[]
    sort(evenArr.begin(), evenArr.end());
 
    // Sort the array oddArr[]
    sort(oddArr.begin(), oddArr.end());
 
    int j = 0, k = 0;
    vector res;
 
    // Combine the elements from evenArr
    // and oddArr in the new array res[]
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0)
            res.push_back(evenArr[j]), j++;
        else
            res.push_back(oddArr[k]), k++;
    }
 
    // Check if the array res[] is
    // sorted or not
    for (int i = 0; i < n - 1; i++) {
        if (res[i] > res[i + 1])
            return false;
    }
 
    // Otherwise, return true
    return true;
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 3, 2, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    if (isSorted(arr, N)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if the array can be
// made sorted by adjacent swapping of
// element such that each array element
// is swapped even number of times
static boolean isSorted(int arr[], int n)
{
    Vector evenArr = new Vector();
    Vector oddArr = new Vector();
 
    // Traverse the given array
    for (int i = 0; i < n; i++) {
 
        // Stores all the even positions
        // elements
        if (i % 2 == 0)
            evenArr.add(arr[i]);
 
        // Stores all the odd positions
        // elements
        else
            oddArr.add(arr[i]);
    }
 
    // Sort the array evenArr[]
    Collections.sort(evenArr);
 
    // Sort the array oddArr[]
    Collections.sort(oddArr);
 
    int j = 0, k = 0;
    Vector res=new Vector();;
 
    // Combine the elements from evenArr
    // and oddArr in the new array res[]
    for (int i = 0; i < n; i++) {
        if (i % 2 == 0) {
            res.add(evenArr.get(j)); j++;
        }
        else {
            res.add(oddArr.get(k)); k++;
        }
    }
 
    // Check if the array res[] is
    // sorted or not
    for (int i = 0; i < n - 1; i++) {
        if (res.get(i) > res.get(i + 1))
            return false;
    }
 
    // Otherwise, return true
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 4, 3, 2, 5 };
    int N = arr.length;
 
    if (isSorted(arr, N)) {
        System.out.print("Yes");
    }
    else {
        System.out.print("No");
    }
 
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program for the above approach
 
# Function to check if the array can be
# made sorted by adjacent swapping of
# element such that each array element
# is swapped even number of times
def isSorted(arr, n):
     
    evenArr = []
    oddArr = []
 
    # Traverse the given array
    for i in range(n):
         
        # Stores all the even positions
        # elements
        if (i % 2 == 0):
            evenArr.append(arr[i])
 
        # Stores all the odd positions
        # elements
        else:
            oddArr.append(arr[i])
 
    # Sort the array evenArr[]
    evenArr.sort()
 
    # Sort the array oddArr[]
    oddArr.sort()
 
    j = 0
    k = 0
    res = []
 
    # Combine the elements from evenArr
    # and oddArr in the new array res[]
    for i in range(n):
        if (i % 2 == 0):
            res.append(evenArr[j])
            j += 1
        else:
            res.append(oddArr[k])
            k += 1
 
    # Check if the array res[] is
    # sorted or not
    for i in range(n - 1):
        if (res[i] > res[i + 1]):
            return False
 
    # Otherwise, return true
    return True
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 4, 3, 2, 5 ]
    N = len(arr)
 
    if (isSorted(arr, N)):
        print("Yes")
    else:
        print("No")
         
# This code is contributed by SURENDRA_GANGWAR


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to check if the array can be
    // made sorted by adjacent swapping of
    // element such that each array element
    // is swapped even number of times
    static bool isSorted(int[] arr, int n)
    {
        List evenArr = new List();
        List oddArr = new List();
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // Stores all the even positions
            // elements
            if (i % 2 == 0)
                evenArr.Add(arr[i]);
 
            // Stores all the odd positions
            // elements
            else
                oddArr.Add(arr[i]);
        }
 
        // Sort the array evenArr[]
        evenArr.Sort();
 
        // Sort the array oddArr[]
        oddArr.Sort();
 
        int j = 0, k = 0;
        List res = new List();
 
        // Combine the elements from evenArr
        // and oddArr in the new array res[]
        for (int i = 0; i < n; i++) {
            if (i % 2 == 0) {
                res.Add(evenArr[j]);
                j++;
            }
            else {
                res.Add(oddArr[k]);
                k++;
            }
        }
 
        // Check if the array res[] is
        // sorted or not
        for (int i = 0; i < n - 1; i++) {
            if (res[i] > res[i + 1])
                return false;
        }
 
        // Otherwise, return true
        return true;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 4, 3, 2, 5 };
        int N = arr.Length;
 
        if (isSorted(arr, N)) {
            Console.Write("Yes");
        }
        else {
            Console.Write("No");
        }
    }
}
 
// This code is contributed by ukasp.


Javascript


输出:
Yes

时间完成: O(N*log N)
辅助空间: O(N)