# 重新排列數組，使偶數位置大於奇數

## 例

`Arr[] = {1, 4, 5, 2, 7}`
`1 7 2 5 4`

## 算法

```1. Traverse the array from 0 to n (length of the array).
1. Check if the position is even or odd if it is even,
2. If arr[i] is greater than the arr[i-1], then swap the array elements.
2. Else, if arr[i] is smaller than the arr[i-1], then swap the array elements.
2. Print the array.```

## 推薦碼

### C ++代碼重新排列數組，使偶數位置大於奇數

```#include<iostream>

using namespace std;

void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void rearrangeEvenPositioned(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
if (i % 2 == 0)
{
if (arr[i] > arr[i - 1])
swap(&arr[i - 1], &arr[i]);
}
else
{
if (arr[i] < arr[i - 1])
swap(&arr[i - 1], &arr[i]);
}
}
}

int main()
{
int arr[] = {1, 4, 5, 2, 7};
int n = sizeof(arr)/sizeof(arr[0]);
rearrangeEvenPositioned(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
```
`1 5 2 7 4`

### Java代碼重新排列數組，使得偶數位置大於奇數

```class rearrangeArray1
{
public static void rearrangeEvenPositioned(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
if (i % 2 == 0)
{
if (arr[i] > arr[i - 1])
{
int temp=arr[i-1];
arr[i-1]=arr[i];
arr[i]=temp;
}
}
else
{
if (arr[i] < arr[i - 1])
{
int temp=arr[i-1];
arr[i-1]=arr[i];
arr[i]=temp;
}
}
}
}
public static void main(String args[])
{
int arr[] = {1, 4, 5, 2, 7};
int n = arr.length;
rearrangeEvenPositioned(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");

}
}

```
`1 5 2 7 4`