Quick actions

cmd+k|ctrl+k

Navigation

Languages

Backend04

Snippet info

Language

JavaScript

Visibility

public

Author

64160280

Created

2023-09-28T08:20:26.722022Z

Updated

2023-09-28T08:20:26.722022Z

function exam04(array){
    //declare variables
    let countSwap = 0;
    let n = array.length;
        for (let i = 1; i < n; i++) {
            // extract the elements 
            let current = array[i];
            let j = i-1; 
            while ((j > -1) && (current < array[j])) {
                array[j+1] = array[j];
                j--;
                countSwap++; // count swap
            }
            array[j+1] = current;
        }
    return countSwap;
  }
  
  function test_01() {
    if (exam04([2, 1, 3, 1, 2]) === 4) {
      console.log("pass");
    } else {
      console.log("fail");
    }
  }
  
  test_01();
INFO