How to move all negative elements to the beginning of array in TypeScript

1 Answer

0 votes
function move_negative_to_beginning(arr : any) {
    let beginning_index = 0;
    
    const size = arr.length;
    
    for (let i = 0; i < size; i++) {
        if (arr[i] < 0) {
            [arr[i], arr[beginning_index]] = [arr[beginning_index], arr[i]];
                
            beginning_index++;
        }
    }
}
        
const arr:number[] = [-1, 8, -6, 21, -3, 4, -2, 18, 15, -30, -40, 9];

move_negative_to_beginning(arr);

console.log(arr);


  
  
  
  
/*
run:
  
[-1, -6, -3, -2, -30, -40, 21, 18, 15, 8, 4, 9]
  
*/


  
 

 



answered Aug 22, 2022 by avibootz

Related questions

...