How to print a list when first element is first max and second element is first min and so on in TypeScript

1 Answer

0 votes
function print_first_max_second_min(arr: number[]) { 
    const size = arr.length;
    
    arr.sort((a, b) => a - b);
 
    let i = 0, j = size - 1, s = ""; 
    while (i < j) { 
        s += arr[j--] + " " + arr[i++] + " ";
    } 
   	
    if (size % 2 != 0) 
        s += arr[i]; 
         
    console.log(s);
} 
 
const arr = [13, 5, 2, 10, 4, 9, 7, 8, 559]; 
     
print_first_max_second_min(arr); 
 
 
 

 
/*
run:
 
"559 2 13 4 10 5 9 7 8" 
 
*/

 



answered Dec 8, 2021 by avibootz
...