After exploring the functionality of Array.prototype.sort
, I decided to experiment with a different approach using bubbleSort to identify any issues.
During each iteration, bubbleSort selects the leftmost element in the unsorted array as the "bubble" and attempts to move it one step to the right at a time. If the element is smaller than its neighboring element on the right, then the right neighbor becomes the new "bubble". This process continues until the largest element reaches the rightmost position among the unsorted elements.
The challenge arises when the elements in my specific dataset are not always comparable to each other. There isn't a clear "biggest" element that can be bubbled to the rightmost position due to partial orderability within the set. While some elements can be ordered, others cannot be compared directly.
To address this issue, I formulated an alternative solution: sorting the orderable elements into segments or chains before merging them together. This modified method, referred to as mergeSort
, deviates from the traditional merge-sort algorithm but serves the purpose effectively.
function mergeSort(arr, compFn) {
let res = [];
while (arr.length > 0) {
res = res.concat(makeChain(arr.splice(0, 1)[0], compFn));
}
return res.filter(n => n);
function makeChain(obj, compFn) {
let res = [obj];
for (let i = 0; i < arr.length; i++) {
if (isEmpty(arr[i])) return;
let flag = compFn(obj, arr[i]);
if (flag < 0) {
res = res.concat(makeChain(arr.splice(i, 1)[0], compFn));
} else if (flag > 0) {
res = makeChain(arr.splice(i, 1)[0], compFn).concat(res);
}
}
return res;
}
}
Subsequently, I utilized the same compareFunction for ordering:
joins = mergeSort(joins, (a, b) => {
if (a.foreignTableName === b.joinTableName) return 1; //b has higher precedence
else if (a.joinTableName === b.foreignTableName) return -1; //a has higher precedence
else return 0; //no change needed
});
This implementation successfully produced the desired sorted array outcome.