Как правильно отсортировать массив объектов быстрой сортировкой?
Как правильно отсортировать массив объектов используя алгоритм быстрой сортировки?
Изначально туда передается массив чисел, сортирует как положено, а если у меня массив объектов, и хочу по полю num его отсортировать именно используя этот алгоритм?
Код самого алгоритма сортировки:
function swap(items, leftIndex, rightIndex){
var temp = items[leftIndex];
items[leftIndex] = items[rightIndex];
items[rightIndex] = temp;
}
function partition(items, left, right) {
var pivot = items[Math.floor((right + left) / 2)], //middle element
i = left, //left pointer
j = right; //right pointer
while (i <= j) {
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
swap(items, i, j); //sawpping two elements
i++;
j--;
}
}
return i;
}
async function quickSortIterative(arr) {
// Creating an array that we'll use as a stack, using the push() and pop() functions
stack = [];
// Adding the entire initial array as an "unsorted subarray"
stack.push(0);
stack.push(arr.length - 1);
// There isn't an explicit peek() function
// The loop repeats as long as we have unsorted subarrays
while(stack[stack.length - 1] >= 0) {
// Extracting the top unsorted subarray
end = stack.pop();
start = stack.pop();
pivotIndex = partition(arr, start, end);
// If there are unsorted elements to the "left" of the pivot,
// we add that subarray to the stack so we can sort it later
if (pivotIndex - 1 > start){
stack.push(start);
stack.push(pivotIndex - 1);
}
// If there are unsorted elements to the "right" of the pivot,
// we add that subarray to the stack so we can sort it later
if (pivotIndex + 1 < end){
stack.push(pivotIndex + 1);
stack.push(end);
}
}
}
arrObj = [ {num: 2, color: 'rgba(163,173,166,0.8)'}
{num: 4, color: 'rgba(163,251,130,0.8)'}
{num: 21, color: 'rgba(163,62,230,0.8)'}
{num: 15, color: 'rgba(163,194,54,0.8)'}
{num: 22, color: 'rgba(163,110,72,0.8)'}
{num: 11, color: 'rgba(163,214,95,0.8)'}
{num: 8, color: 'rgba(163,116,219,0.8)'}
{num: 55, color: 'rgba(163,155,163,0.8)'}
{num: 3, color: 'rgba(163,94,127,0.8)'}
{num: 5, color: 'rgba(163,8,62,0.8)'}]
quickSortIterative(arrObj)