Я нашел эту статью на среде, и я пытаюсь выяснить, что на самом деле делает код.
это код:
helper
const defaultComparator = (a, b) => {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
};
функция сортировки
const quickSort = (
unsortedArray,
comparator = defaultComparator
) => {
// Create a sortable array to return.
const sortedArray = [ ...unsortedArray ];
// Recursively sort sub-arrays.
const recursiveSort = (start, end) => {
// If this sub-array is empty, it's sorted.
if (end - start < 1) {
return;
}
const pivotValue = sortedArray[end];
let splitIndex = start;
for (let i = start; i < end; i++) {
const sort = comparator(sortedArray[i], pivotValue);
// This value is less than the pivot value.
if (sort === -1) {
// If the element just to the right of the split index,
// isn't this element, swap them.
if (splitIndex !== i) {
const temp = sortedArray[splitIndex];
sortedArray[splitIndex] = sortedArray[i];
sortedArray[i] = temp;
}
// Move the split index to the right by one,
// denoting an increase in the less-than sub-array size.
splitIndex++;
}
// Leave values that are greater than or equal to
// the pivot value where they are.
}
// Move the pivot value to between the split.
sortedArray[end] = sortedArray[splitIndex];
sortedArray[splitIndex] = pivotValue;
// Recursively sort the less-than and greater-than arrays.
recursiveSort(start, splitIndex - 1);
recursiveSort(splitIndex + 1, end);
};
// Sort the entire array.
recursiveSort(0, unsortedArray.length - 1);
return sortedArray;
};
Итак, я потратил некоторое время, чтобы выяснить, как работает splitIndex
.Он начинается с 0 и увеличивается на 1 только в том случае, если текущий элемент в цикле for меньше точки поворота.Когда мы встречаем число, большее, чем значение pivot, splitIndex остается на своем значении, и значение i
увеличивается.На следующем шаге, если число также меньше, чем точка, мы поменяем их местами
Так, например, с этим массивом: [2,4,65,1,15]
splitIndex и i во время цикла for равны, пока мы не получим число65. Здесь splitIndex не увеличивается, и когда мы достигаем числа 1, мы меняем 1 и 65.
Я не являюсь носителем английского языка, поэтому я не совсем понимаю, что автор имеет в виду:
// If the element just to the right of the split index,
// isn't this element, swap them.
Мне еще нужно полностью понять, как работает код, но, по-вашему, правильно ли я сказал?
Спасибо