In the script above, we declare a sort_arr function which accepts an input array of elements as a parameter. It sorts the array in-place and then returns the number of write operations.
Let's pass it our test array and see the results.
xxxxxxxxxx49
console.log('Operations: ', operations);let inputArray = [9, 4, 6, 8, 14, 3];let inputArrayCopy = [inputArray];​function sortArr(inputArray) { let operations = 0;​ for (let cycleIndex = 0; cycleIndex < inputArray.length; cycleIndex++) { let number = inputArray[cycleIndex]; let currentIndex = cycleIndex;​ for (let j = cycleIndex + 1; j < inputArray.length; j++) { if (inputArray[j] < number) { currentIndex++; } }​ if (currentIndex === cycleIndex) { continue; }​ while (number === inputArray[currentIndex]) { currentIndex++; } [inputArray[currentIndex], number] = [number, inputArray[currentIndex]]; operations++;​ while (currentIndex !== cycleIndex) { currentIndex = cycleIndex;​OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

