📌  相关文章
📜  重新排列数组,使偶数索引元素更小,奇数索引元素更大

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

重新排列数组,使偶数索引元素更小,奇数索引元素更大

给定一个数组,重新排列数组,使得:

  1. 如果索引 i 是偶数,则 arr[i] <= arr[i+1]
  2. 如果索引 i 是奇数,则 arr[i] >= arr[i+1]

注意:可以有多个答案。
例子:

Input  : arr[] = {2, 3, 4, 5} 
Output : arr[] = {2, 4, 3, 5}
Explanation : Elements at even indexes are
smaller and elements at odd indexes are greater
than their next elements

Note : Another valid answer
is arr[] = {3, 4, 2, 5}

Input  :arr[] = {6, 4, 2, 1, 8, 3}
Output :arr[] = {4, 6, 1, 8, 2, 3}

这个问题类似于对数组进行波形排序。
一个简单的解决方案是按降序对数组进行排序,然后从第二个元素开始,交换相邻的元素。
一个有效的解决方案是遍历数组并根据给定条件交换元素。
如果我们有一个长度为 n 的数组,那么我们从索引 0 迭代到 n-2 并检查给定的条件。
在任何时间点,如果 i 是偶数并且 arr[i] > arr[i+1],那么我们交换 arr[i] 和 arr[i+1]。同样,如果 i 是奇数并且
arr[i] < arr[i+1],然后我们交换 arr[i] 和 arr[i+1]。
对于给定的示例:
重新排列之前,arr[] = {2, 3, 4, 5}
开始迭代数组直到索引 2(因为 n = 4)

重新排列后,arr[] = {2, 4, 3, 5}

C++
// CPP code to rearrange an array such that
// even index elements are smaller and odd
// index elements are greater than their
// next.
#include 
using namespace std;
 
void rearrange(int* arr, int n)
{
    for (int i = 0; i < n - 1; i++) {
        if (i % 2 == 0 && arr[i] > arr[i + 1])
            swap(arr[i], arr[i + 1]);
 
        if (i % 2 != 0 && arr[i] < arr[i + 1])
            swap(arr[i], arr[i + 1]);
    }
}
 
/* Utility that prints out an array in
   a line */
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
 
    cout << endl;
}
 
/* Driver function to test above functions */
int main()
{
    int arr[] = { 6, 4, 2, 1, 8, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Before rearranging: \n";
    printArray(arr, n);
 
    rearrange(arr, n);
 
    cout << "After rearranging: \n";
    printArray(arr, n);
 
    return 0;
}


Java
// Java code to rearrange an array such
// that even index elements are smaller
// and odd index elements are greater
// than their next.
 
class GFG {
 
    static void rearrange(int arr[], int n)
    {
 
        int temp;
        for (int i = 0; i < n - 1; i++) {
            if (i % 2 == 0 && arr[i] > arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
            if (i % 2 != 0 && arr[i] < arr[i + 1]) {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }
 
    /* Utility that prints out an array in
    a line */
    static void printArray(int arr[], int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
 
        System.out.println();
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 6, 4, 2, 1, 8, 3 };
        int n = arr.length;
 
        System.out.print("Before rearranging: \n");
        printArray(arr, n);
 
        rearrange(arr, n);
 
        System.out.print("After rearranging: \n");
        printArray(arr, n);
    }
}
 
// This code is contributed by Anant Agarwal.


Python3
# Python code to rearrange
# an array such that
# even index elements
# are smaller and odd
# index elements are
# greater than their
# next.
 
def rearrange(arr, n):
 
    for i in range(n - 1):
        if (i % 2 == 0 and arr[i] > arr[i + 1]):
         
            temp = arr[i]
            arr[i]= arr[i + 1]
            arr[i + 1]= temp
         
        if (i % 2 != 0 and arr[i] < arr[i + 1]):
          
            temp = arr[i]
            arr[i]= arr[i + 1]
            arr[i + 1]= temp
            
  
# Utility that prints out an array in
# a line
def printArray(arr, size):
 
    for i in range(size):
        print(arr[i], " ", end ="")
  
    print()
 
# Driver code
 
arr = [ 6, 4, 2, 1, 8, 3 ]
n = len(arr)
  
print("Before rearranging: ")
printArray(arr, n)
  
rearrange(arr, n)
  
print("After rearranging:")
printArray(arr, n);
 
# This code is contributed
# by Anant Agarwal.


C#
// C# code to rearrange an array such
// that even index elements are smaller
// and odd index elements are greater
// than their next.
using System;
 
class GFG {
 
    static void rearrange(int[] arr, int n)
    {
        int temp;
        for (int i = 0; i < n - 1; i++) {
            if (i % 2 == 0 && arr[i] > arr[i + 1])
            {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
             
            if (i % 2 != 0 && arr[i] < arr[i + 1])
            {
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }
        }
    }
 
    /* Utility that prints out an array in
    a line */
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
 
        Console.WriteLine();
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 6, 4, 2, 1, 8, 3 };
        int n = arr.Length;
 
        Console.WriteLine("Before rearranging: ");
        printArray(arr, n);
 
        rearrange(arr, n);
 
        Console.WriteLine("After rearranging: ");
        printArray(arr, n);
    }
}
 
// This code is contributed by vt_m.


PHP
 $arr[$i + 1])
            swap($arr[$i], $arr[$i + 1]);
 
        if ($i % 2 != 0 &&
            $arr[$i] < $arr[$i + 1])
            swap($arr[$i], $arr[$i + 1]);
    }
}
 
/* Utility that prints out
an array in a line */
function printArray(&$arr, $size)
{
    for ($i = 0; $i < $size; $i++)
        echo $arr[$i] . " ";
 
    echo "\n";
}
 
// Driver Code
$arr = array(6, 4, 2, 1, 8, 3 );
$n = sizeof($arr);
 
echo "Before rearranging: \n";
printArray($arr, $n);
 
rearrange($arr, $n);
 
echo "After rearranging: \n";
printArray($arr, $n);
 
// This code is contributed
// by ChitraNayal
?>


Javascript


输出:

Before rearranging:
6 4 2 1 8 3
After rearranging:
4 6 1 8 2 3

时间复杂度: O(n)