使用C++将数组重新排列为最大最小形式

使用C++将数组重新排列为最大最小形式

我们得到一个排序数组。我们需要以最大、最小形式排列这个数组,即第一个元素是最大元素,第二个元素是最小元素,第三个元素是第二个最大元素,第四个元素是第二个最小元素,依此类推,例如 -

Input : arr[ ] = { 10, 20, 30, 40, 50, 60 } Output : { 60, 10, 50, 20, 40, 30 } Explanation : array is rearranged in the form { 1st max, 1st min, 2nd max, 2nd min, 3rd max, 3rd min } Input : arr [ ] = { 15, 17, 19, 23, 36, 67, 69 } Output : { 69, 15, 67, 17, 36, 19, 23 }登录后复制

找到解决方案的方法

有一种方法可以以最大和最小形式重新排列数组form -

双指针方法

使用两个变量,min和max,这里将指向最大和最小元素,并创建一个相同大小的新空数组存储重新排列的数组。现在迭代数组,如果迭代元素位于偶数索引,则将 arr[max] 元素添加到空数组并将 max 减 1。如果元素位于奇数索引,则将 arr[min] 元素添加到空数组并将 min 加 1。执行此操作,直到 max 小于 min。

示例

#include using namespace std; int main () { int arr[] = { 1, 2, 3, 4, 5, 6 }; int n = sizeof (arr) / sizeof (arr[0]); // creating a new array to store the rearranged array. int final[n]; // pointing variables to initial and final element index. int min = 0, max = n - 1; int count = 0; // iterating over the array until max is less than or equals to max. for (int i = 0; min