📌  相关文章
📜  检查是否可以通过重新排列奇数和偶数索引元素来对数组进行排序

📅  最后修改于: 2021-05-17 18:07:36             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是检查是否可以使用以下操作对数组进行排序:

  • 如果i&1 = 1j&1 = 1则交换(arr [i],arr [j])
  • 如果i&1 = 0j&1 = 0则交换(arr [i],arr [j])

例子:

天真的方法:这个想法是找到偶数索引或奇数索引的最小元素,并在当前元素的索引分别为偶数或奇数的情况下从当前元素交换它。

  • 遍历数组arr []并执行以下操作:
    • 如果当前索引为偶数,则遍历其余的偶数索引。
    • 查找偶数索引元素中存在的最小元素。
    • 用当前数组元素交换最小值。
  • 对所有奇数索引元素也重复上述步骤。
  • 完成上述操作后,如果对数组进行了排序,则可以对数组进行排序。
  • 否则,将无法对数组进行排序。

下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Function to check if array
// can be sorted or not
bool isSorted(int arr[], int n)
{
    for(int i = 0; i < n - 1; i++)
    {
        if (arr[i] > arr[i + 1])
            return false;
    }
    return true;
}
 
// Function to check if given
// array can be sorted or not
bool sortPoss(int arr[], int n)
{
     
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int idx = -1;
        int minVar = arr[i];
 
        // Traverse remaining elements
        // at indices separated by 2
        int j = i;
         
        while (j < n)
        {
             
            // If current element
            // is the minimum
            if (arr[j] < minVar)
            {
                minVar = arr[j];
                idx = j;
            }
            j = j + 2;
        }
 
        // If any smaller minimum exists
        if (idx != -1)
        {
             
            // Swap with current element
            swap(arr[i], arr[idx]);
        }
    }
     
    // If array is sorted
    if (isSorted(arr, n))
        return true;
 
    // Otherwise
    else
        return false;
}
 
// Driver Code
int main()
{
     
    // Given array
    int arr[] = { 3, 5, 1, 2, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
     
    if (sortPoss(arr, n))
        cout << "True";
      else
        cout << "False";
         
    return 0;
}
 
// This code is contributed by ukasp


Java
class GFG{
     
// Function to check if array
// can be sorted or not
public static boolean isSorted(int arr[], int n)
{
    for(int i = 0; i < n - 1; i++)
    {
        if (arr[i] > arr[i + 1])
            return false;
    }
    return true;
}
 
// Function to check if given
// array can be sorted or not
public static boolean sortPoss(int arr[], int n)
{
     
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int idx = -1;
        int minVar = arr[i];
 
        // Traverse remaining elements
        // at indices separated by 2
        int j = i;
         
        while (j < n)
        {
             
            // If current element
            // is the minimum
            if (arr[j] < minVar)
            {
                minVar = arr[j];
                idx = j;
            }
            j = j + 2;
        }
 
        // If any smaller minimum exists
        if (idx != -1)
        {
             
            // Swap with current element
            int t;
            t = arr[i];
            arr[i] = arr[idx];
            arr[idx] = t;
        }
    }
     
    // If array is sorted
    if (isSorted(arr, n))
        return true;
 
    // Otherwise
    else
        return false;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given array
    int arr[] = { 3, 5, 1, 2, 6 };
    int n = arr.length;
     
    if (sortPoss(arr, n))
        System.out.println("True");
      else
        System.out.println("False");
}
}
 
// This code is contributed by SoumikMondal


Python3
# Function to check if array
# can be sorted or not
def isSorted(arr):
  for i in range(len(arr)-1):
    if arr[i]>arr[i + 1]:
      return False
  return True
 
# Function to check if given
# array can be sorted or not
def sortPoss(arr):
   
  # Traverse the array
  for i in range(len(arr)):
 
    idx = -1
    minVar = arr[i]
     
    # Traverse remaining elements
    # at indices separated by 2
    for j in range(i, len(arr), 2):
       
      # If current element
      # is the minimum
      if arr[j]


C#
using System;
 
class GFG{
     
// Function to check if array
// can be sorted or not
public static bool isSorted(int[] arr, int n)
{
    for(int i = 0; i < n - 1; i++)
    {
        if (arr[i] > arr[i + 1])
            return false;
    }
    return true;
}
 
// Function to check if given
// array can be sorted or not
public static bool sortPoss(int[] arr, int n)
{
     
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int idx = -1;
        int minVar = arr[i];
 
        // Traverse remaining elements
        // at indices separated by 2
        int j = i;
         
        while (j < n)
        {
             
            // If current element
            // is the minimum
            if (arr[j] < minVar)
            {
                minVar = arr[j];
                idx = j;
            }
            j = j + 2;
        }
 
        // If any smaller minimum exists
        if (idx != -1)
        {
             
            // Swap with current element
            int t;
            t = arr[i];
            arr[i] = arr[idx];
            arr[idx] = t;
        }
    }
     
    // If array is sorted
    if (isSorted(arr, n))
        return true;
 
    // Otherwise
    else
        return false;
}
 
// Driver code
static public void Main()
{
     
    // Given array
    int[] arr = { 3, 5, 1, 2, 6 };
    int n = arr.Length;
     
    if (sortPoss(arr, n))
        Console.WriteLine("True");
    else
        Console.WriteLine("False");
}
}
 
// This code is contributed by offbeat


Python3
# Python Program to implement
# the above approach
 
# Function to check if array can
# be sorted by given operations
def sortPoss(arr):
   
  # Copy contents
  # of the array
  dupArr = list(arr)
   
  # Sort the duplicate array
  dupArr.sort()
   
  evenOrg = []
  evenSort = []
   
  # Traverse the array
  for i in range(0, len(arr), 2):
     
    # Append even-indexed elements
    # of the original array
    evenOrg.append(arr[i])
     
    # Append even-indexed elements
    # of the duplicate array
    evenSort.append(dupArr[i])
   
  # Sort the even-indexed elements
  evenOrg.sort()
  evenSort.sort()
   
  # Return true if even-indexed
  # elements are identical
  return evenOrg == evenSort
 
# Driver Code
 
# Given array
arr = [3, 5, 1, 2, 6]
 
print(sortPoss(arr))


输出:
True

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

高效方法:想法是检查是否可以利用我们可以使用交换操作的方式排列所有偶数索引和奇数索引元素的事实。

  • 初始化一个数组,例如dupArr [] ,以存储给定数组的内容。
  • 对数组dupArr []排序。
  • 检查原始数组中的所有偶数索引元素是否与dupArr []中的偶数索引元素相同。
  • 如果发现为真,则可以进行排序。否则,将无法分类。

下面是上述方法的实现:

Python3

# Python Program to implement
# the above approach
 
# Function to check if array can
# be sorted by given operations
def sortPoss(arr):
   
  # Copy contents
  # of the array
  dupArr = list(arr)
   
  # Sort the duplicate array
  dupArr.sort()
   
  evenOrg = []
  evenSort = []
   
  # Traverse the array
  for i in range(0, len(arr), 2):
     
    # Append even-indexed elements
    # of the original array
    evenOrg.append(arr[i])
     
    # Append even-indexed elements
    # of the duplicate array
    evenSort.append(dupArr[i])
   
  # Sort the even-indexed elements
  evenOrg.sort()
  evenSort.sort()
   
  # Return true if even-indexed
  # elements are identical
  return evenOrg == evenSort
 
# Driver Code
 
# Given array
arr = [3, 5, 1, 2, 6]
 
print(sortPoss(arr))
输出:
True

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