Answer the question
In order to leave comments, you need to log in
Is the number of moves counted correctly in insertion sort?
Insertion sorting of an array is implemented in JavaScript:
const sort = (arr) => {
let compCounter = 0; // счетчик сравнений
let movementCounter = 0; // счетчик перемещений элементов
const arrLength = arr.length;
for (let i = 1; i < arrLength; i++) {
for (let j = i; j > 0; j--) {
if (arr[j - 1] > arr[j]) {
const temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
movementCounter += 3;
}
compCounter += 1;
}
}
console.log('Количество сравнений: ', compCounter);
console.log('Количество перемещений: ', movementCounter);
};
Answer the question
In order to leave comments, you need to log in
If elements are moved, the counter is incremented by 3 because there are 3 element operations.
[ arr[j - 1], arr[j] ] = [ arr[j], arr[j - 1] ];
swap(arr, j - 1, j); // функция меняет местами элементы, но как именно - вам неизвестно
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question