Home  >  Article  >  Backend Development  >  How to use PHP to make the even-numbered elements in an array larger than the odd-numbered elements?

How to use PHP to make the even-numbered elements in an array larger than the odd-numbered elements?

藏色散人
藏色散人Original
2019-03-26 10:49:512251browse


#This article mainly introduces how to use PHP to rearrange an array and make the elements in even positions larger than the elements in odd positions.

How to use PHP to make the even-numbered elements in an array larger than the odd-numbered elements?

Given an array A containing n elements, sort the array according to the following relationship:

If i is even, then A[i] >= A[i-1].

If i is an odd number, then A[i] <= A[i-1].

Print the result array.

Example:

输入:A[] = {1,2,2,1}
输出:1,2,1,2

注:
对于第一个元素,1 1,i = 2是偶数。
第三个元素1 1,i = 4是偶数。

输入:A[] = {1,3,2}
输出:1 3 2
注:
这里,数组也按照条件排序。
1 1和2 < 3。

Observe that the array consists of [n/2] elements in even positions. If we assign the largest [n/2] elements to even positions and the remaining elements to odd positions, our problem is solved. Because the element in the odd position is always smaller than the element in the even position because it is the largest element and vice versa. Sort the array and assign the first [n/2] elements at even positions.

The following is the PHP implementation method of the above method:

<?php 
// PHP程序重新排列数组中的元素,使偶数位置的元素大于奇数位置的元素
  
function assign($a, $n) 
{ 
      
    //排序数组
    sort($a); 
  
    $p = 0; $q = $n - 1; 
    for ($i = 0; $i < $n; $i++)  
    { 
          
        // 分配具有最大元素的索引
        if (($i + 1) % 2 == 0) 
            $ans[$i] = $a[$q--]; 
  
        // 用剩余元素分配奇数索引
        else
            $ans[$i] = $a[$p++]; 
    } 
  
    for ($i = 0; $i < $n; $i++)  
        echo($ans[$i] . " "); 
} 
  
$A = array( 1, 3, 2, 2, 5 ); 
$n = sizeof($A); 
assign($A, $n);

Output:

  1 5 2 3 2

Related recommendations: "PHP Tutorial"

This article is about using PHP to rearrange an array and make the elements in even positions larger than the elements in odd positions. I hope it will be helpful to friends in need!


The above is the detailed content of How to use PHP to make the even-numbered elements in an array larger than the odd-numbered elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn