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

📅  最后修改于: 2021-09-06 05:55:00             🧑  作者: Mango

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

  • Swap(arr[i], arr[j]) ,如果i & 1 = 1并且j & 1 = 1
  • Swap(arr[i], arr[j]) ,如果i & 1 = 0j & 1 = 0

例子:

朴素方法:这个想法是找到偶数索引或奇数索引的最小元素,如果当前元素的索引分别是偶数或奇数,则将其与当前元素交换。

  • 遍历数组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


Javascript


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[] 中的偶数索引元素相同。
  • 如果发现是真的,那么排序是可能的。否则,排序是不可能的。

下面是上述方法的实现:

蟒蛇3

# 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)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live