This commit is contained in:
Lars Kotthoff 2024-07-17 10:36:35 +09:00 committed by GitHub
commit 057f38b3c0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 21 additions and 9 deletions

View File

@ -24,7 +24,7 @@ export default function kruskal(graph) {
*/
compareCallback: (graphEdgeA, graphEdgeB) => {
if (graphEdgeA.weight === graphEdgeB.weight) {
return 1;
return 0;
}
return graphEdgeA.weight <= graphEdgeB.weight ? -1 : 1;

View File

@ -14,13 +14,25 @@ export default class QuickSort extends Sort {
return array;
}
// Init left and right arrays.
// Init left, center, and right arrays.
const leftArray = [];
const rightArray = [];
const centerArray = [];
// Take the first element of array as a pivot.
const pivotElement = array.shift();
const centerArray = [pivotElement];
// Take the median element of first, mid, and last elements.
let pivotElement = array[0];
const mid = Math.floor(array.length / 2);
if ((this.comparator.lessThan(array[mid], array[array.length - 1])
&& this.comparator.greaterThan(array[mid], array[0]))
|| (this.comparator.greaterThan(array[mid], array[array.length - 1])
&& this.comparator.lessThan(array[mid], array[0]))) {
pivotElement = array[mid];
} else if ((this.comparator.lessThan(array[array.length - 1], array[mid])
&& this.comparator.greaterThan(array[array.length - 1], array[0]))
|| (this.comparator.greaterThan(array[array.length - 1], array[mid])
&& this.comparator.lessThan(array[array.length - 1], array[0]))) {
pivotElement = array[array.length - 1];
}
// Split all array elements between left, center and right arrays.
while (array.length) {

View File

@ -8,10 +8,10 @@ import {
} from '../../SortTester';
// Complexity constants.
const SORTED_ARRAY_VISITING_COUNT = 190;
const NOT_SORTED_ARRAY_VISITING_COUNT = 62;
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 190;
const EQUAL_ARRAY_VISITING_COUNT = 19;
const SORTED_ARRAY_VISITING_COUNT = 66;
const NOT_SORTED_ARRAY_VISITING_COUNT = 83;
const REVERSE_SORTED_ARRAY_VISITING_COUNT = 66;
const EQUAL_ARRAY_VISITING_COUNT = 20;
describe('QuickSort', () => {
it('should sort array', () => {