In this tutorial, we’ll find the second largest element in an array.
for approch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | array arr = [10,52,64,51,23] #sample array n = array_length(arr) largest = arr[0] secondLargest = arr[0] for i=0 to i<n-1 step 1 then if arr[i] > largest then secondLargest = largest largest = arr[i] end if if arr[i] > secondLargest and arr[i] < largest then secondLargest = arr[i] end if end for print secondLargest |
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $arr = [10,52,64,51,23]; $largest = $arr[0]; $secondLargest = $arr[0]; for($i=0;$i<count($arr);$i++) { if($arr[$i] > $largest) { $secondLargest = $largest; $largest = $arr[$i]; if ($arr[$i] > $secondLargest && $arr[$i] < $largest) { $secondLargest = $arr[$i]; } } } echo $secondLargest."<br>"; |
each approch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | arr = [10,52,64,51,23] //Traverse an array each arr as number then //If it's greater than the value of max if number > largest then secondLargest = largest largest = $number end if //If array number is greater than secondMax and less than max if number > secondLargest and number < largest then secondLargest = number end if end each print secondLargest |
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $arr = [10,52,64,51,23]; //Traverse an array foreach($arr as $number) { //If it's greater than the value of max if($number > $largest) { $secondLargest = $largest; $largest = $number; } //If array number is greater than secondMax and less than max if($number > $secondLargest && $number < $largest) { $secondLargest = $number; } } echo $secondLargest; |