Quick sort | const quickSort = (arr) => {
if (arr.length <= 1) return arr;
const pivot = new Date(arr[Math.floor(arr.length / 2)]['date']).getTime();
const left = arr.filter(row => new Date(row['date']).getTime() < pivot);
const middle = arr.filter(row => new Date(row['date']).getTime() === pivot);
const right = arr.filter(row => new Date(row['date']).getTime() > pivot);
return [...quickSort(left), ...middle, ...quickSort(right)];
};
const sortedData = quickSort(dummyData)
| ready |
Merge sort | const mergeSort = (arr) => {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
};
const merge = (left, right) => {
const result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
const leftDate = new Date(left[leftIndex]['date']).getTime();
const rightDate = new Date(right[rightIndex]['date']).getTime();
if (leftDate < rightDate) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
return [...result, ...left.slice(leftIndex), ...right.slice(rightIndex)];
};
const sortedData = mergeSort(dummyData)
| ready |
Heap sort | function heapSort(arr) {
const n = arr.length;
for (let i = Math.floor(n / 2); i >= 0; i--) {
heapify(arr, n, i);
}
for (let i = n - 1; i > 0; i--) {
[arr[0], arr[i]] = [arr[i], arr[0]];
heapify(arr, i, 0);
}
return arr;
}
function heapify(arr, n, i) {
let largest = i;
const left = 2 * i + 1;
const right = 2 * i + 2;
if (left < n && new Date(arr[left]['date']) > new Date(arr[largest]['date'])) {
largest = left;
}
if (right < n && new Date(arr[right]['date']) > new Date(arr[largest]['date'])) {
largest = right;
}
if (largest !== i) {
[arr[i], arr[largest]] = [arr[largest], arr[i]];
heapify(arr, n, largest);
}
}
const sortedData = heapSort(dummyData)
| ready |
Radix sort | function radixSort(arr) {
const getMax = (arr) => Math.max(...arr.map(item => new Date(item['date']).getTime()));
const max = getMax(arr);
for (let exp = 1; Math.floor(max / exp) > 0; exp *= 10) {
countingSort(arr, exp);
}
}
function countingSort(arr, exp) {
const output = new Array(arr.length);
const count = new Array(10).fill(0);
for (const item of arr) {
const index = Math.floor(new Date(item['date']).getTime() / exp) % 10;
count[index]++;
}
for (let i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
for (let i = arr.length - 1; i >= 0; i--) {
const index = Math.floor(new Date(arr[i]['date']).getTime() / exp) % 10;
output[count[index] - 1] = arr[i];
count[index]--;
}
for (let i = 0; i < arr.length; i++) {
arr[i] = output[i];
}
}
const sortedData = radixSort(dummyData)
| ready |