I have the following code:
let arr = [];
for (i = 14; i <= 31; i++) {
let d = "2018-08-" + String(i);
arr.push({
date: d
});
}
arr.sort((a, b) => a.date - b.date);
console.log(arr);
I know sort() is supposed to be used only with numbers
I know that comparing strings with - is a bad idea
I already localized and fixed the original bug in my code, but...
There is something that fascinates me about this buggy code: the result.
Subtracting a string from another string gives NaN, so I'd expect the array to stay the same (14, 15, 16, 17... 31), or maybe to get completely flipped (31, 30, 29, 28... 14).
Instead, the actual (consistent) result is
I'm very curious about knowing why exactly sort() is outputting that sequence of strings. Why 31, 15 and 23 get moved, and why do they get moved to those particular positions?
This behavior is probably easier to understand with a simpler array.
For example:
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr.sort(() => NaN)
console.log(arr)
In chrome this returns an array order like: [0,11,2,3,4,5,1,7,8,9,10,6].
This is peculiar, but if you look at the implementation of sorting in the V8 code you will find a mix of quicksort and insertion sort. In fact if will recursively call quicksort until the arrays being recursed on have a length less than 10, then it will switch to insertions sort.
The way quick sort chooses the pivot explains the behavior you're seeing. Here's a snippet with the slightly truncated code from V8:
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
function comparefn(a,b){
return NaN
}
function InsertionSort(a, from, to) {
for (var i = from + 1; i < to; i++) {
var element = a[i];
for (var j = i - 1; j >= from; j--) {
var tmp = a[j];
var order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
};
function QuickSort(a, from, to) {
var third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
InsertionSort(a, from, to);
return;
}
third_index = from + ((to - from) >> 1);
// Find a pivot as the median of first, last and middle element.
var v0 = a[from];
var v1 = a[to - 1];
var v2 = a[third_index];
var c01 = comparefn(v0, v1);
if (c01 > 0) {
// v1 < v0, so swap them.
var tmp = v0;
v0 = v1;
v1 = tmp;
} // v0 <= v1.
var c02 = comparefn(v0, v2);
if (c02 >= 0) {
// v2 <= v0 <= v1.
var tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
// v0 <= v1 && v0 < v2
var c12 = comparefn(v1, v2);
if (c12 > 0) {
// v0 <= v2 < v1
var tmp = v1;
v1 = v2;
v2 = tmp;
}
}
// v0 <= v1 <= v2
a[from] = v0;
a[to - 1] = v2;
var pivot = v1;
var low_end = from + 1; // Upper bound of elements lower than pivot.
var high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
// From low_end to i are elements equal to pivot.
// From i to high_start are elements that haven't been compared yet.
partition: for (var i = low_end + 1; i < high_start; i++) {
var element = a[i];
var order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start == i) break partition;
var top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
if (to - high_start < low_end - from) {
QuickSort(a, high_start, to);
to = low_end;
} else {
QuickSort(a, from, low_end);
from = high_start;
}
}
};
// run it
QuickSort(arr, 0, arr.length)
console.log(arr)
If you look at this, especially the way the pivot is chosen and when it switches to insertion sort, you will see why the results are ordered the way they are.
When the compare function always returns NaN, all the ifs in the code are bypassed that look like this:
var c12 = comparefn(v1, v2);
if (c12 > 0) { /* etc /*}
Meaning the whole sort reduces to the smaller:
arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
function comparefn(a,b){
//console.log(a, b)
return NaN
}
function QuickSort(a, from, to) {
var third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
return;
}
third_index = from + ((to - from) >> 1);
// Find a pivot as the median of first, last and middle element.
var v0 = a[from];
var v1 = a[to - 1];
var v2 = a[third_index];
a[from] = v0;
a[to - 1] = v2;
var pivot = v1;
var low_end = from + 1; // Upper bound of elements lower than pivot.
var high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
partition: for (var i = low_end + 1; i < high_start; i++) {
var element = a[i];
}
if (to - high_start < low_end - from) {
QuickSort(a, high_start, to);
to = low_end;
} else {
QuickSort(a, from, low_end);
from = high_start;
}
}
};
QuickSort(arr, 0, arr.length)
console.log(arr)
Related
Please find my quicksort implementation below in javascript.
const A = [4, 6, 2, 5, 7, 9, 1, 3];
const partition = function(l, h) {
let pivot = A[l];
let i = l;
let j = h;
while(A[i] <= pivot) {
i++;
}
while(A[j] > pivot) {
j--;
}
if (i < j) {
let temp = A[i];
A[i] = A[j];
A[j] = temp;
}
let temp1 = A[l];
A[l] = A[j];
A[j] = temp1;
return j;
}
const quickSort = function (l, h) {
if (l < h) {
let piIdx = partition(l, h);
console.log('the pidx is ', piIdx);
quickSort(l, piIdx - 1);
quickSort(piIdx + 1, h);
}
}
quickSort(0, A.length - 1);
console.log('array after quicksort call ', A);
The output is as below:
[ 1, 2, 3, 5, 7, 9, 6, 4 ]
The last set of elements haven't been sorted properly. Could anyone please have a look and let me know the problem.
thanks
The problem is that your partition function will at most perform 2 swaps. This cannot be right.
The process of swapping (the first one in your code) should be repeated until i has arrived at j.
Not the problem, but as the function is mutating A, that should be a parameter of the function -- that is best practice.
Here is an update of your function, with a test script below it that tests the implementation for 1000 arrays that are randomly shuffled:
const partition = function(A, l, h) { // A is parameter
let pivot = A[l];
let i = l;
let j = h;
while (true) { // Keep going
while(A[i] <= pivot) {
i++;
}
while(A[j] > pivot) {
j--;
}
if (i >= j) break; // All done
let temp = A[i];
A[i] = A[j];
A[j] = temp;
}
A[l] = A[j];
A[j] = pivot; // We already know A[l], no need for temp
return j;
}
const quickSort = function (A, l, h) { // A is parameter
if (l < h) {
let piIdx = partition(A, l, h);
quickSort(A, l, piIdx - 1);
quickSort(A, piIdx + 1, h);
}
}
// Test the implementation
function shuffle(a) {
let i = a.length;
while (i) {
let j = Math.floor(Math.random() * i--);
[a[i], a[j]] = [a[j], a[i]];
}
}
const A = [...Array(50).keys()]; // is sorted
const ref = A.toString(); // string to compare solution with
for (let attempt = 0; attempt < 1000; attempt++) {
shuffle(A);
quickSort(A, 0, A.length - 1);
if (A.toString() != ref) {
console.log('Error: array not sorted after quicksort call ', ...A);
break;
}
}
console.log("all tests done");
You are halfway there ,
you are iterating the low and high but those both along with there swap needs to be in a loop that goes from low all the way to high
meaning until high does not overlap low , the loop will keep on going .
and once the loop breaks you got your index of putting the pivot
you also need to have a pivot index that will help you at the end to swap the j with the pivot index;
so it should be like this
var pivotIndex=l;
while(i<j){
while(A[i] <= pivot) {
i++;
}
while(A[j] > pivot) {
j--;
}
if (i < j) {
let temp = A[i];
A[i] = A[j];
A[j] = temp;
}
let temp1 = A[l];
A[l] = A[j];
A[j] = temp1;
}
[nums[pivotIndex],nums[j]]=[nums[j],[nums[pivotIndex]]
return j;}
I hope this help
I currently acheive shuffle one of array without duplicated with previous value of next value.
However, I don't think my method is good. I think there are better way.
Firstly, I will describe what the array looks like.
it's an array of object with property {answer,url,category} and there are duplicated item in the array. think as [A,A,B,B,C,C] , A,B,C as object here.
As EzioMerce pointed out, in this array, object will always has equal amount of numbers. such if there are 3 A, will definitely have 3 B and C. It will not have array as such [A,A,A,B]
I need the array to shuffle until there is no consecutive object next to each other such as [A,B,C,B,A,C]
Here is my solution (which I have tested 40 times without consecutive object):
getShuffleWords(array: Card[]) {
//First shuffle..
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor( Math.random() * (i - 1));
if (j > 0) {
//make sure there are no simliar value around position i and j
if (array[i]?.answer !== array[j - 1]?.answer
&& array[i]?.answer !== array[j + 1]?.answer
&& array[i]?.answer !== array[j - 1]?.answer
&& array[i]?.answer !== array[j + 1]?.answer) {
[array[i], array[j]] = [array[j], array[i]];
}
} else {
if (array[i]?.answer !== array[j + 1]?.answer) {
[array[i], array[j]] = [array[j], array[i]];
}
}
}
const before = [...array];
console.log(before);
//Checking duplicate and swap with other value
for (let x = 0; x < array.length; x++){
if (array[x].answer == array[x + 1]?.answer) {
console.log(x,array[x])
for (let y = 0; y < array.length; y++){
//make sure there are no simliar value around position x and y
if (array[y]?.answer !== array[x]?.answer
&& array[y + 1]?.answer !== array[x].answer
&& array[y - 1]?.answer !== array[x].answer
&& array[y]?.answer !== array[x+1]?.answer
&& array[y]?.answer !== array[x-1]?.answer
) {
console.log(y, array[y]);
if (x < y) {
[array[x], array[y]] = [array[y], array[x]];
} else {
[array[y], array[x]] = [array[x], array[y]];
}
break;
}
}
}
}
//just another caculate if there is duplication left (for testing purpose)
let dup = 0;
for (let x = 0; x < array.length; x++){
if (array[x].answer == array[x + 1]?.answer) {
dup++;
}
}
console.log(array, dup);
return array;
}
However, in the //First shuffle.. there are always has some consecutive object exisited in the array. thats why I repeat another checking and replace the value.
How would I improve my method. and why my first shuffle does not work perfectly?
You can try this way. It also works if arr will be an array of objects
const arr = [1, 2, 3, 1, 2, 3, 1, 2, 3];
const shuffle = (arr) => {
const uniqueArr = [...(new Set(arr))];
const shuffledArr = [];
let countOfOneObj = 0;
for (const obj of arr) {
if (obj === arr[0]) ++countOfOneObj;
};
const getRandomObj = () => {
const i = Math.floor(Math.random() * uniqueArr.length);
return uniqueArr[i];
}
for (let i = 0; i < countOfOneObj; ++i) {
let usedObjs = []
for (let j = 0; j < uniqueArr.length; ++j) {
const obj = getRandomObj();
if (
usedObjs.includes(obj) ||
shuffledArr[shuffledArr.length - 1] === obj
) {
--j;
continue;
}
usedObjs.push(obj);
shuffledArr.push(obj);
}
usedObjs = [];
}
return shuffledArr;
}
console.log(shuffle(arr));
You could shuffle an array of indices of same grouped values until you got a result which has no same neighbour indices.
const
fy = array => { // fisher-yates, adapted from https://stackoverflow.com/a/59837259/1447675
let i = array.length;
while (--i) {
const j = Math.floor(Math.random() * (i + 1));
[array[j], array[i]] = [array[i], array[j]];
}
},
shuffle = array => {
do fy(array);
while (array.some((v, i, a) => v === a[i + 1]))
};
indices = [0, 0, 0, 1, 1, 1, 2, 2];
shuffle(indices);
console.log(...indices);
I was trying to implement merge sort algorithm in JavaScript without built in methods like slice(), splice(), etc. It doesn’t work exactly I wish. Can you help me to figure out where is bug hidden? Getting output [3, 5, 5, 3, 7] instead of [3, 5, 5, 7, 8].
// Merge Sort implementation
// sort implementation
function sort(arr, start, mid, end) {
// Creation and filling the temp arrays
let lArray = [];
let rArray = [];
for (let i = 0; i <= mid - start; i++) {
lArray[i] = arr[start + i];
}
for (let j = 0; j <= end - mid - 1; j++) {
rArray[j] = arr[mid + 1 + j];
}
// Sorting and updating current array
let i = 0;
let j = 0;
let k = start;
while (i < lArray.length && j < rArray.length) {
if (lArray[i] < rArray[j]) {
arr[k] = lArray[i];
i++;
k++;
} else {
arr[k] = rArray[j];
j++;
k++;
}
}
// Handling last element in lArray or rArray
i < lArray.length ? arr[k] = lArray[i] : arr[k] = rArray[j];
}
// Recursive Merge Sort
function recursiveMergeSort(arr, start, end) {
if (start < end) {
let mid = Math.floor(((end) + start) / 2);
//console.log(start, end, mid);
recursiveMergeSort(arr, start, mid);
recursiveMergeSort(arr, mid + 1, end);
sort(arr, start, mid, end);
}
}
function mergeSort(arr) {
let start = 0;
let end = arr.length - 1;
recursiveMergeSort(arr, start, end);
return (arr)
}
console.log(mergeSort([5, 8, 3, 7, 5]));
// Handling last element in lArray or rArray is not correct.
After merging arrays you have to check the rests and copy untreated tail if it does exist
while (i < lArray.length) {
arr[k] = lArray[i];
i++;
k++;
}
while (j < rArray.length) {
arr[k] = rArray[j];
j++;
k++;
}
Replacing ternary operator by this code gives correct results for given data
Example of a somewhat optimized version of top down merge sort. It does a one time allocation of a working array and uses a pair of mutually recursive functions to change the direction of merge for each level of recursion. Takes about 1/4 second to sort 1 million pseudo-random integers on my system:
// merge sort top down
function merge(a, b, bgn, mid, end) {
var i = bgn // left: a[bgn,mid)
var j = mid // right: a[mid,end)
var k = bgn // index for b[]
while(true){
if(a[i] <= a[j]){ // if left <= right
b[k++] = a[i++] // copy left
if(i < mid) // if not end of left
continue // continue back to while
do // else copy rest of right
b[k++] = a[j++]
while(j < end)
break // and break
} else { // else left > right
b[k++] = a[j++] // copy right
if(j < end) // if not end of right
continue // continue back to while
do // else copy rest of left
b[k++] = a[i++]
while(i < mid)
break // and break
}
}
}
function sortatob(a, b, bgn, end) { // sort a to b
if ((end-bgn) < 2){
b[bgn] = a[bgn]
return
}
var mid = Math.floor(bgn + (end - bgn) / 2)
sortatoa(a, b, bgn, mid)
sortatoa(a, b, mid, end)
merge(a, b, bgn, mid, end)
}
function sortatoa(a, b, bgn, end) { // sort a to a
if ((end-bgn) < 2)
return
var mid = Math.floor(bgn + (end - bgn) / 2)
sortatob(a, b, bgn, mid)
sortatob(a, b, mid, end)
merge(b, a, bgn, mid, end)
}
function mergesort(a) { // entry function
if(a.length < 2)
return
var b = new Array(a.length) // allocate temp array
sortatoa(a, b, 0, a.length) // start with sort a to a
}
var a = new Array(1000000)
for (i = 0; i < a.length; i++) {
a[i] = parseInt(Math.random() * 1000000000)
}
console.time('measure')
mergesort(a)
console.timeEnd('measure')
for (i = 1; i < a.length; i++) {
if(a[i-1] > a[i]){
console.log('error')
break
}
}
I´m trying to implement a quicksort algorithm for an int array in JavaScript.
I´ve got a problem in my code. The first few ints get sorted well but at the end of the sortet array there is always one integer which is placed many times although its only one time in the array which should be sorted. Hopefully someone will find my fault.
Thanks.
function quicksort(array) {
var randomPlace = Math.round(Math.random() * array.length);
var pivotelement = array[randomPlace];
left = new Array;
right = new Array;
for (var i = 0; i < array.length; i++) {
if (array[i] < pivot) {
left[left.length] = array[i];
} else {
right[right.length] = array[i];
}
}
if ((left.length == 0 || left.length == 1) && (right.length == 0 || right.length == 1)) {
return left.concat(right);
} else if (left.length == 0 || left.length == 1) {
return (left.concat((quicksort(right))));
} else if (right.length == 0 || right.length == 1) {
return ((quicksort(left)).concat(right));
} else {
return (quicksort(left)).concat((quicksort(right)));
}
}
Beside some nameming confusion, like pivotelement vs pivot and Math.round vs Math.floor, you need to tackle the problem of for example [1, 1, 1] which is always returning left = [] and right = [1, 1, 1], that calls quicksort([1, 1, 1]) ad infinitum.
To overcome this problem, you need to check for empty left and with right every element, if it is equal to the random pivot. Then return right, without calling quicksort again.
function quicksort(array) {
var randomPlace = Math.floor(Math.random() * array.length),
pivot = array[randomPlace],
left = [],
right = [],
i;
for (i = 0; i < array.length; i++) {
(array[i] < pivot ? left : right).push(array[i]);
}
console.log(pivot, JSON.stringify(array), JSON.stringify(left), JSON.stringify(right));
// prevent looping forever
if (!left.length && right.every(function (v) { return v === pivot; })) {
return right;
}
if (left.length <= 1 && right.length <= 1) {
return left.concat(right);
}
if (left.length <= 1) {
return left.concat(quicksort(right));
}
if (right.length <= 1) {
return quicksort(left).concat(right);
}
return quicksort(left).concat(quicksort(right));
}
console.log(quicksort([2, 7, 4, 8, 3, 11, 49, 20, 10, 1, 1, 1]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another solution would be to separate the array into three arrays, one for smaller values, one for equal values and one for greater values. Then sort only the smaller and greater arrays.
function quicksort(array) {
var randomPlace = Math.floor(Math.random() * array.length),
pivotValue = array[randomPlace],
left = [],
pivot = [],
right = [],
i;
for (i = 0; i < array.length; i++) {
if (array[i] === pivotValue) {
pivot.push(array[i]);
continue;
}
(array[i] < pivotValue ? left : right).push(array[i]);
}
console.log(pivotValue, JSON.stringify(array), JSON.stringify(left), JSON.stringify(pivot), JSON.stringify(right));
if (left.length <= 1 && right.length <= 1) {
return left.concat(pivot, right);
}
if (left.length <= 1) {
return left.concat(pivot, quicksort(right));
}
if (right.length <= 1) {
return quicksort(left).concat(pivot, right);
}
return quicksort(left).concat(pivot, quicksort(right));
}
console.log(quicksort([2, 7, 4, 8, 3, 11, 49, 20, 10, 1, 1, 1]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
heres a short version of quick sort written in JS exactly as it is seen in Intro To Algorithms, hope this helps!
var partition = function (arr, low, high) {
var x = arr[high]
var i = low - 1
for (var j = low; j <= high - 1; j++) {
if (arr[j] <= x) {
i++
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
var temp = arr[i + 1]
arr[i + 1] = arr[high]
arr[high] = temp
return i + 1
}
var quickSort = function (arr, low, high) {
if (low < high) {
index = partition(arr,low,high)
if (low < index-1) quickSort(arr,low,index-1)
if (index+1 < high) quickSort(arr,index+1,high)
}
}
var list2 = [1000,13,12,1001,82,1,2,4,3,0]
console.log(quickSort(list2,0,list2.length))
also on my GitHub
I think you are identifying the randomPlace wrongly. It returns undefined some times because you're using Math.round().
Try this instead:
var randomPlace = Math.floor(Math.random() * array.length);
Also, use the following code when initializing left, and right:
var left = new Array();
var right = new Array();
Also, you need to change the pivot in array[i] < pivot to pivotElement.
You can see my complete fiddle here
it's a simple code, but returns different results in Andriod and Iphone.
var str = [1,2,3,4,5].sort(function () {
return -1;
})
document.write(str);
In MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) it says
If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
So the result should be 1,2,3,4,5.
But is Iphone it shows 5,4,3,2,1
Here is a link for you to try this code. http://www.madcoder.cn/demos/ios-test.html
And after I did more and more test. I found Iphone is doing a different sorting.
Here is a link shows how sort works: http://www.madcoder.cn/demos/ios-test2.html
The javascript engines use different algorithms for their sort function. Since the compare function doesn't compare values, you get the result of the inner workings of the different algorithms instead of having a sorted result.
Looking at the source code of V8 engine (Chrome) and JavaScriptCore (which seems to be used by Safari, or at least the sort function gives the same result, so I guess it uses the same kind of algorithm), you can view the functions that are being used.
Not that it might not be exactly the functions used, what's important is that the algorithms are different. They give the same result if you actually compare values, but if not, the result is dependent on the way they operate, not on the function itself. At least not completely.
Here's V8 engine sorting function. You'll see that for arrays bigger than 10 elements, the algorithm isn't the same, so the result for arrays smaller than 10 elements is different than for those bigger than 10 elements.
You can find following algorithms here: https://code.google.com/p/chromium/codesearch#chromium/src/v8/src/js/array.js&q=array&sq=package:chromium&dr=C
comparefn = function(a, b) {
return -1
}
var InsertionSort = function InsertionSort(a, from, to) {
for (var i = from + 1; i < to; i++) {
var element = a[i];
for (var j = i - 1; j >= from; j--) {
var tmp = a[j];
var order = comparefn(tmp, element);
if (order > 0) {
a[j + 1] = tmp;
} else {
break;
}
}
a[j + 1] = element;
}
console.log(a);
}
var GetThirdIndex = function(a, from, to) {
var t_array = new InternalArray();
// Use both 'from' and 'to' to determine the pivot candidates.
var increment = 200 + ((to - from) & 15);
var j = 0;
from += 1;
to -= 1;
for (var i = from; i < to; i += increment) {
t_array[j] = [i, a[i]];
j++;
}
t_array.sort(function(a, b) {
return comparefn(a[1], b[1]);
});
var third_index = t_array[t_array.length >> 1][0];
return third_index;
}
var QuickSort = function QuickSort(a, from, to) {
var third_index = 0;
while (true) {
// Insertion sort is faster for short arrays.
if (to - from <= 10) {
InsertionSort(a, from, to);
return;
}
if (to - from > 1000) {
third_index = GetThirdIndex(a, from, to);
} else {
third_index = from + ((to - from) >> 1);
}
// Find a pivot as the median of first, last and middle element.
var v0 = a[from];
var v1 = a[to - 1];
var v2 = a[third_index];
var c01 = comparefn(v0, v1);
if (c01 > 0) {
// v1 < v0, so swap them.
var tmp = v0;
v0 = v1;
v1 = tmp;
} // v0 <= v1.
var c02 = comparefn(v0, v2);
if (c02 >= 0) {
// v2 <= v0 <= v1.
var tmp = v0;
v0 = v2;
v2 = v1;
v1 = tmp;
} else {
// v0 <= v1 && v0 < v2
var c12 = comparefn(v1, v2);
if (c12 > 0) {
// v0 <= v2 < v1
var tmp = v1;
v1 = v2;
v2 = tmp;
}
}
// v0 <= v1 <= v2
a[from] = v0;
a[to - 1] = v2;
var pivot = v1;
var low_end = from + 1; // Upper bound of elements lower than pivot.
var high_start = to - 1; // Lower bound of elements greater than pivot.
a[third_index] = a[low_end];
a[low_end] = pivot;
// From low_end to i are elements equal to pivot.
// From i to high_start are elements that haven't been compared yet.
partition: for (var i = low_end + 1; i < high_start; i++) {
var element = a[i];
var order = comparefn(element, pivot);
if (order < 0) {
a[i] = a[low_end];
a[low_end] = element;
low_end++;
} else if (order > 0) {
do {
high_start--;
if (high_start == i) break partition;
var top_elem = a[high_start];
order = comparefn(top_elem, pivot);
} while (order > 0);
a[i] = a[high_start];
a[high_start] = element;
if (order < 0) {
element = a[i];
a[i] = a[low_end];
a[low_end] = element;
low_end++;
}
}
}
if (to - high_start < low_end - from) {
QuickSort(a, high_start, to);
to = low_end;
} else {
QuickSort(a, from, low_end);
from = high_start;
}
}
};
InsertionSort([1, 2, 3, 4, 5], 0, 5);
//QuickSort is recursive and calls Insertion sort, so you'll have multiple logs for this one
QuickSort([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 0, 13);
//You'll see that for arrays bigger than 10, QuickSort is called.
var srt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13].sort(function() {
return -1
})
console.log(srt)
And JavaScriptCore uses merge sort. You can find this algorithm here:
http://trac.webkit.org/browser/trunk/Source/JavaScriptCore/builtins/ArrayPrototype.js
function min(a, b) {
return a < b ? a : b;
}
function merge(dst, src, srcIndex, srcEnd, width, comparator) {
var left = srcIndex;
var leftEnd = min(left + width, srcEnd);
var right = leftEnd;
var rightEnd = min(right + width, srcEnd);
for (var dstIndex = left; dstIndex < rightEnd; ++dstIndex) {
if (right < rightEnd) {
if (left >= leftEnd || comparator(src[right], src[left]) < 0) {
dst[dstIndex] = src[right++];
continue;
}
}
dst[dstIndex] = src[left++];
}
}
function mergeSort(array, valueCount, comparator) {
var buffer = [];
buffer.length = valueCount;
var dst = buffer;
var src = array;
for (var width = 1; width < valueCount; width *= 2) {
for (var srcIndex = 0; srcIndex < valueCount; srcIndex += 2 * width)
merge(dst, src, srcIndex, valueCount, width, comparator);
var tmp = src;
src = dst;
dst = tmp;
}
if (src != array) {
for (var i = 0; i < valueCount; i++)
array[i] = src[i];
}
return array;
}
console.log(mergeSort([1, 2, 3, 4, 5], 5, function() {
return -1;
}))
Again these may not be exactly the functions used in each browser, but it shows you how different algorithms will behave if you don't actually compare values.