Why result of the function call is undefined? - javascript

Why array can't be displayed immediately after swap function call in JS? Why result of the function call is undefined?
const swap = (arr) => {
for (let i = 0; i < arr.length - 1; i++) {
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
r = [...Array(10)].map( (_, i) => (i + 1) * 3);
console.log(r); // --> Array [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
//swap(r);
// why array can't be displayed immediately after swap function call?
console.log( swap(r) ); // --> displays undefined but the swap function worked out
console.log(r); // --> Array [ 6, 9, 12, 15, 18, 21, 24, 27, 30, 3 ]
I think it's because the swap function returns nothing but I'm not sure. But
swap(r);
console.log(r);
works fine.

You don't need to return anything and leave your function swap as it. The passed array is a reference of r = [...Array(10)].map((_, i) => (i + 1) * 3) so, every modification will modify that array after the function swap ends.
Just print the array console.log(r);.
const swap = (arr) => {
for (let i = 0; i < arr.length - 1; i++) {
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
r = [...Array(10)].map((_, i) => (i + 1) * 3);
console.log(r); // --> Array [ 3, 6, 9, 12, 15, 18, 21, 24, 27, 30 ]
swap(r);
// why array can't be displayed immediately after swap function call?
// console.log(swap(r)); // --> displays undefined but the swap function worked out
console.log(r); // --> Array [ 6, 9, 12, 15, 18, 21, 24, 27, 30, 3 ]
.as-console-wrapper { max-height: 100% !important; top: 0; }

Yes you are correct, it's because you are trying to output the result of the swap function call but you are not returning anything specific. So the default result is undefined.
If you want to output the array after the swap, then return that in your function like so:
const swap = (arr) => {
for (let i = 0; i < arr.length - 1; i++) {
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
return arr;
}
r = [...Array(10)].map((_, i) => (i + 1) * 3);
console.log(swap(r));
Ultimately it is up to you to decide how you want the function to work. As you have identified there is no need to return anything at all as long as you don't try and use the result of the function call.
With regards to why it doesn't automatically return the array, well you have to remember that a function can do lots of different things to many objects. There would be no way to know which object or value should automatically be returned, so it doesn't make sense for it to try and do anything magic like that. If you want something returned, then make sure you return it.

Yes you are right; you should use return arr; but I think what you want is rotating the array.
arr = new Array(10).fill().map( (_, i) => (i + 1) * 3);
console.log(arr);
res = [...arr.slice(1),arr[0]]; // prettier but can be dramatically slow on large arrays
// or for even faster one :
rotate = (arr) => !(arr.push(arr.shift())) || arr;
// or
/*const rotate = (arr) => {
var first = arr[0];
for(var c = 0, l = arr.length - 1; c < l;)
arr[c] = arr[++c];
arr[arr.length-1] = first;
return arr;
}*/
console.log(res);
console.log(rotate(arr));

Related

How can I return "1-5" if the array is [1,2,3,4,5] in JavaScript?

I am trying to make a program that returns ["1-5"] if I give [1,2,3,4,5].
I have made it but I can't filter it. So I want a code that will filter my output code. Or any code that is better than mine.
let array = [1,2,3,5,6,7,8,10,11, 34, 56,57,];
let x = [];
for(let i = 0; i < array.length; i++){
for(let j = 0; j < array.length; j++){
if(array[i] + j == array[j]){
x.push(array[i] + "-" + array[j]);
}
if(array[j] > array[i] + j && array[j + 1]){
let y = array.slice(j, array.length)
array = y;
i, j = 0;
}
if(array[i] - array[i + 1] != -1 && array[i + 1] - array[i] != 1 && array[i + 1] != undefined){
x.push(array[i]);
}
}
}
console.log(x);
The phrasing of the question makes this somewhat difficult to answer, but based on your code snippet I can gather that you are either:
Attempting to find the range of the entire array OR
Attempting to find contiguous ranges within the array
Based on these interpretations, you could answer this question as follows:
function detectRange(a) {
// clone a
const b = [...a]
// remove first value
const min = max = b.splice(0, 1)[0]
// compute range
const range = b.reduce(({min, max}, i) => {
if(i < min) min = i
if(i > max) max = i
return { min, max }
}, {min, max})
return range
}
function detectRanges(a) {
// clone a
const b = [...a]
// remove first value
const min = max = b.splice(0, 1)[0]
// init ranges array
const ranges = [ ]
// compute ranges
const range = b.reduce(({min, max}, i) => {
if(i === max + 1) {
return {min , max: i}
} else {
ranges.push({min, max})
return {min: i, max: i}
}
}, {min, max})
// push the remaining range onto the array
ranges.push(range)
return ranges
}
function printRange(r) {
console.log(`["${r.min}-${r.max}"]`)
}
function printRanges(r) {
r.forEach(i => {
printRange(i)
})
}
// detect and print range of whole array
printRange(detectRange([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))
// detect and print only contiguous ranges within array
printRanges(detectRanges([1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57]))
If you assume that the list is sorted, we only need to traverse the list sequentially. There's no need to have double-nested loops. If you maintain sufficient states, you can determine whether you are in a group and you merely manage the start versus the last element in the group.
To simplify things I made use of ES6 string interpolation ${start}-${last}.
let array = [1,2,3,5,6,7,8,10,11, 34, 56,57];
let result = [ ];
let hasStart = false;
let start = 0;
let last = 0;
for (let num of array) {
if (!hasStart) {
hasStart = true;
last = start = num;
continue;
}
if (num === last + 1) {
last = num;
continue;
}
result.push( start === last ? start : `${start}-${last}` );
last = start = num;
}
if (hasStart) {
result.push( start === last ? start : `${start}-${last}` );
}
console.log(result);
Input: [1,2,3,4,5]
Output: ["1-5"]
So I assume you want to get string in format:
["smallestelement-largestelement"]
var input1 = [1,2,3,4,5]
console.log( "["+'"'+Math.min(...input1)+"-"+Math.max(...input1)+'"'+"]")
If what you want is string in format:
["firstelement-lastelement"]
var input1 = [1,2,3,4,5]
console.log( "["+'"'+input1[0]+"-"+input1.pop()+'"'+"]")
If you have an integer array, and if you want to output the range, you could natively sort() it (you can also provide rules for sorting) and use shift() for the first element and slice(-1) for the last:
let arr = [4,1,5,3].sort();
console.log(arr.shift()+'-'+arr.slice(-1));
As said in the comments, you should clarify if you wish "1-57" for the snippet array, or describe your use case more broadly.
const array = [1, 2, 3, 5, 6, 7, 8, 10, 11, 34, 56, 57];
let s = null;
const result = array.sort((a, b) => a - b).reduce((p, c, i, arr) => {
if (!s) s = c;
if (c + 1 !== arr[i + 1]) {
p.push(s === c ? s : `${s}-${c}`);
s = null;
}
return p
}, [])
console.log(result);

If statement not returning anything inside of two for loops

I'm trying to return an array inside of an if statement, but nothing is returning. When I console.log( [ i, j ] ), it works fine.
const twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i++) {
for (let j = 0; j < nums.length; j++) {
if (nums[i] + nums[j] === target) {
return [ i, j ];
}
}
}
};
twoSum([ 2, 7, 11, 15 ], 9);
I understand that this is not the most efficient way to solve this problem, but I'm just learning the basics and I'm very confused as to why this is not returning anything.
It should return [0, 1].
If you want to display the result in the console, try:
console.log(twoSum([ 2, 7, 11, 15 ], 9));
maybe you can write it this way so it easier to read. having two for loops is difficult to handle. We can optimize this if we know that the array only have positive numbers.
const twoSum = (nums, target) => {
let found = null;
nums.some((n, i) => {
// here you figure where you are looking for.
const lookingFor = target - n;
const idx = nums.indexOf(lookingFor, i);
if (idx !== -1) {
found = [i, idx];
return true;
}
return false;
});
return found;
};
console.log(twoSum([ 2, 7, 11, 15 ], 9));

Fibonacci Sequence - Starts at a specific # in javascript

//var myInputNumber=10;
function fibonacci(num) {
let fib = [1,1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}
console.log(fibonacci(10));
Complete javascript newbie here. I need help with a homework project. I have this work and displays up to the x (for easier display) Fibonacci numbers.
Here is the results from the above code: [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]
What I want to be able to do is specify the starting number/point (>=10, for example), and have it only display numbers from that point going forward.
So if my input number is 10, I want this result [ 13, 21, 34, 55, 89 ].
Use array filter and in the callback function return those element which are greater than the number passed as argument
function fibonacci(num) {
let fib = [1, 1];
for (let i = 2; i <= num; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib.filter(function(item) {
return item > num
});
}
console.log(fibonacci(10));
just add another variable then
function fibonacci(num) {
let result = [];
let fib = [1,1];
for (let i = 2; i <= num; i++) {
let temp = fib[i-1] + fib[i-2];
fib.push(temp);
if(result>=num)
result.push(temp)
}
return result;
}
You may also want to define a limit to stop. The rest is pretty much similar to your existing code
function fibonacci(num, limit) {
let fib = [1,1];
for (let i = num; i <= limit; i++) {
fib.push(fib[i-1] + fib[i-2]);
}
return fib;
}

javascript map and reduce array list

I have a list of array in this format
data = [[1,2,3,4,5,6,7,8,9,10],
[11,12,13,14,15,16,17,18,19,20],
[21,22,23,24,25,26,27,28,29,30]]
I want the output in this format
[[11/1, 12/2,13/3,14/4,15/5,16/6,17/7,18/8,19/9,20/10],
[21/11,22/12,23/13,24/14,25/15,26/16,27/17,28/18,29/19,30/20]]
I have used for loop and this is how it looks
const totalData = data.length;
for(var i =0 ; i < totalData ; i++){
for(var j =0; j < data[i].length; j++){
console.log(data[i+1][j]/data[i][j]);
}
}
I want to convert this using javascript map and reduce? is there any possible ways?
Thank you
for loops aren't bad practice, they just don't fit in a functional style of programming. The following solution presupposes that the arrays' lengths are equal:
const data = [
[1,2,3,4,5,6,7,8,9,10],
[11,12,13,14,15,16,17,18,19,20],
[21,22,23,24,25,26,27,28,29,30]
];
const result = data.map((arr, index) => {
const next = data[index + 1];
if (!Array.isArray(next)) {
return;
}
return arr.map((item, i) => next[i] / item);
}).filter(Boolean);
console.log(result);
I am sure you can figure out what to do if the arrays' lengths are not equal.
You could use a single reduce and map the items for a new array.
var data = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]],
result = [];
data.reduce((a, b) => (result.push(a.map((c, i) => b[i] / c)), b));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You need to create separated functions for each task:
/**
* Combine 2 arrays
* #param Array a
* #param Array b
*/
function combineArrays(a, b) {
var combined = [];
for (var i = 0; i < a.length; i++)
combined.push(a[i] / b[i]);
return combined;
}
/**
* Combine an group of arrays
* #param Array group
*/
function combineGroup(group) {
var newGroup = [];
for (var i = 0; i < group.length - 1; i++)
newGroup.push(combineArrays(group[i], group[i + 1]));
return newGroup;
}
The first function combine 2 arrays only.
The second function combine many arrays and return what you want.
if the lengths are not equal, the items in the tail of the longer one are ignored.
data = [
[1,2,3,4,5,6,7,8,9,10],
[11,12,13,14,15,16,17,18,19,20],
[21,22,23,24,25,26,27,28,29,30]
];
result = data.reduce((acc,current,i)=>{
var ret;
if(data[i].length <= data[i-1].length)
ret = data[i].map((item,j)=>(item / data[i-1][j]));
else
ret = data[i-1].map((item,j)=>(data[i][j] / item));
if(i==1)
return [ret]
else
return acc.concat([ret])
})
console.log(result)

JavaScript quicksort

I have been looking around the web for a while and I am wondering if there is a 'stable' defacto implementation of quicksort that is generally used? I can write my own but why reinvent the wheel...
Quicksort (recursive)
function quicksort(array) {
if (array.length <= 1) {
return array;
}
var pivot = array[0];
var left = [];
var right = [];
for (var i = 1; i < array.length; i++) {
array[i] < pivot ? left.push(array[i]) : right.push(array[i]);
}
return quicksort(left).concat(pivot, quicksort(right));
};
var unsorted = [23, 45, 16, 37, 3, 99, 22];
var sorted = quicksort(unsorted);
console.log('Sorted array', sorted);
You can easily "stabilize" an unstable sort using a decorate-sort-undecorate pattern
function stableSort(v, f)
{
if (f === undefined) {
f = function(a, b) {
a = ""+a; b = ""+b;
return a < b ? -1 : (a > b ? 1 : 0);
}
}
var dv = [];
for (var i=0; i<v.length; i++) {
dv[i] = [v[i], i];
}
dv.sort(function(a, b){
return f(a[0], b[0]) || (a[1] - b[1]);
});
for (var i=0; i<v.length; i++) {
v[i] = dv[i][0];
}
}
the idea is to add the index as last sorting term so that no two elements are now "the same" and if everything else is the same the original index will be the discriminating factor.
Put your objects into an array.
Call Array.sort(). It's very fast.
var array = [3,7,2,8,2,782,7,29,1,3,0,34];
array.sort();
console.log(array); // prints [0, 1, 2, 2, 29, 3, 3, 34, 7, 7, 782, 8]
Why does that print in lexicographic order? That's how array.sort() works by default, e.g. if you don't provide a comparator function. Let's fix this.
var array = [3,7,2,8,2,782,7,29,1,3,0,34];
array.sort(function (a, b)
{
return a-b;
});
console.log(array); // prints [0, 1, 2, 2, 3, 3, 7, 7, 8, 29, 34, 782]
Quick Sort (ES6)
function quickSort(arr) {
if (arr.length < 2) {
return arr;
}
const pivot = arr[Math.floor(Math.random() * arr.length)];
let left = [];
let right = [];
let equal = [];
for (let val of arr) {
if (val < pivot) {
left.push(val);
} else if (val > pivot) {
right.push(val);
} else {
equal.push(val);
}
}
return [
...quickSort(left),
...equal,
...quickSort(right)
];
}
Few notes:
A random pivot keeps the algorithm efficient even when the data is sorted.
As much as it nice to use Array.filter instead of using for of loop, like some of the answers here, it will increase time complexity (Array.reduce can be used instead though).
A Functional equivalent
In celebration of Functional Javascript, which appears to be the in thing
at the moment, especially given ES6+ wonderful syntactic sugar additions. Arrow functions and destructuring I propose a very clean, short functional equivalent of the quicksort function. I have not tested it for performance or compared it to the built-in quicksort function but it might help those who are struggling to understand the practical use of a quicksort. Given its declarative nature it is very easy to see what is happening as oppose to how it works.
Here is a JSBin version without comments https://jsbin.com/zenajud/edit?js,console
function quickSortF(arr) {
// Base case
if (!arr.length) return []
// This is a ES6 addition, it uses destructuring to pull out the
// first value and the rest, similar to how other functional languages
// such as Haskell, Scala do it. You can then use the variables as
// normal below
const [head, ...tail] = arr,
// here we are using the arrow functions, and taking full
// advantage of the concise syntax, the verbose version of
// function(e) => { return e < head } is the same thing
// so we end up with the partition part, two arrays,
// one smaller than the pivot and one bigger than the
// pivot, in this case is the head variable
left = tail.filter( e => e < head),
right = tail.filter( e => e >= head)
// this is the conquer bit of divide-and-conquer
// recursively run through each left and right array
// until we hit the if condition which returns an empty
// array. These results are all connected using concat,
// and we get our sorted array.
return quickSortF(left).concat(head, quickSortF(right))
}
const q7 = quickSortF([11,8,14,3,6,2,7])
//[2, 3, 6, 7, 8, 11, 14]
const q8 = quickSortF([11,8,14,3,6,2,1, 7])
//[1, 2, 3, 6, 7, 8, 11, 14]
const q9 = quickSortF([16,11,9,7,6,5,3, 2])
//[2, 3, 5, 6, 7, 9, 11, 16]
console.log(q7,q8,q9)
The comments should provide enough if it is already not clear what is happening. The actual code is very short without comments, and you may have noticed I am not a fan of the semicolon. :)
In this blog http://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/ which has pointed out that
Array.sort is implemented in quicksort or merge sort internaly.
Quicksort is generally considered to be efficient and fast and so is
used by V8 as the implementation for Array.prototype.sort() on arrays
with more than 23 items. For less than 23 items, V8 uses insertion
sort[2]. Merge sort is a competitor of quicksort as it is also
efficient and fast but has the added benefit of being stable. This is
why Mozilla and Safari use it for their implementation of
Array.prototype.sort().
and when using Array.sort,you should return -1 0 1 instead of true or false in Chrome.
arr.sort(function(a,b){
return a<b;
});
// maybe--> [21, 0, 3, 11, 4, 5, 6, 7, 8, 9, 10, 1, 2, 12, 13, 14, 15, 16, 17, 18, 19, 20, 22]
arr.sort(function(a,b){
return a > b ? -1 : a < b ? 1 : 0;
});
// --> [22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
var array = [8, 2, 5, 7, 4, 3, 12, 6, 19, 11, 10, 13, 9];
quickSort(array, 0, array.length -1);
document.write(array);
function quickSort(arr, left, right)
{
var i = left;
var j = right;
var tmp;
pivotidx = (left + right) / 2;
var pivot = parseInt(arr[pivotidx.toFixed()]);
/* partition */
while (i <= j)
{
while (parseInt(arr[i]) < pivot)
i++;
while (parseInt(arr[j]) > pivot)
j--;
if (i <= j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
return arr;
}
Using ES6 rest, spread:
smaller = (a, list) => list.filter(x => x <= a)
larger = (a, list) => list.filter(x => x > a)
qsort = ([x, ...list]) => (!isNaN(x))
? [...qsort(smaller(x, list)), x, ...qsort(larger(x, list))]
: []
This algorithm work almost as fast as the default implementation
of Array.prototype.sort in chrome.
function quickSort(t){
_quickSort(t,0,t.length-1,0,t.length-1);
}
function _quickSort(t, s, e, sp, ep){
if( s>=e ) return;
while( sp<ep && t[sp]<t[e] ) sp++;
if( sp==e )
_quickSort(t,s,e-1,s,e-1);
else{
while(t[ep]>=t[e] && sp<ep ) ep--;
if( sp==ep ){
var temp = t[sp];
t[sp] = t[e];
t[e] = temp;
if( s!=sp ){
_quickSort(t,s,sp-1,s,sp-1);
}
_quickSort(t,sp+1,e,sp+1,e);
}else{
var temp = t[sp];
t[sp] = t[ep];
t[ep] = temp;
_quickSort(t,s,e,sp+1,ep);
}
}
}
quickSort time (ms): 738
javaScriptSort time (ms): 603
var m = randTxT(5000,500,-1000,1000);
VS(m);
function VS(M){
var t;
t = Date.now();
for(var i=0;i<M.length;i++){
quickSort(M[i].slice());
}console.log("quickSort time (ms): "+(Date.now()-t));
t = Date.now();
for(var i=0;i<M.length;i++){
M[i].slice().sort(compare);
}console.log("javaScriptSort time (ms): "+(Date.now()-t));
}
function compare(a, b) {
if( a<b )
return -1;
if( a==b )
return 0;
return 1;
}
function randT(n,min,max){
var res = [], i=0;
while( i<n ){
res.push( Math.floor(Math.random()*(max-min+1)+min) );
i++;
}
return res;
}
function randTxT(n,m,min,max){
var res = [], i=0;
while( i<n ){
res.push( randT(m,min,max) );
i++;
}
return res;
}
Yet another quick sort demonstration, which takes middle of the array as pivot for no specific reason.
const QuickSort = function (A, start, end) {
//
if (start >= end) {
return;
}
// return index of the pivot
var pIndex = Partition(A, start, end);
// partition left side
QuickSort(A, start, pIndex - 1);
// partition right side
QuickSort(A, pIndex + 1, end);
}
const Partition = function (A, start, end) {
if (A.length > 1 == false) {
return 0;
}
let pivotIndex = Math.ceil((start + end) / 2);
let pivotValue = A[pivotIndex];
for (var i = 0; i < A.length; i++) {
var leftValue = A[i];
//
if (i < pivotIndex) {
if (leftValue > pivotValue) {
A[pivotIndex] = leftValue;
A[i] = pivotValue;
pivotIndex = i;
}
}
else if (i > pivotIndex) {
if (leftValue < pivotValue) {
A[pivotIndex] = leftValue;
A[i] = pivotValue;
pivotIndex = i;
}
}
}
return pivotIndex;
}
const QuickSortTest = function () {
const arrTest = [3, 5, 6, 22, 7, 1, 8, 9];
QuickSort(arrTest, 0, arrTest.length - 1);
console.log("arrTest", arrTest);
}
//
QuickSortTest();
I really thought about this question. So first I found the normal search mode and wrote.
let QuickSort = (arr, low, high) => {
if (low < high) {
p = Partition(arr, low, high);
QuickSort(arr, low, p - 1);
QuickSort(arr, p + 1, high);
}
return arr.A;
}
let Partition = (arr, low, high) => {
let pivot = arr.A[high];
let i = low;
for (let j = low; j <= high; j++) {
if (arr.A[j] < pivot) {
[arr.A[i], arr.A[j]] = [arr.A[j], arr.A[i]];
i++;
}
}
[arr.A[i], arr.A[high]] = [arr.A[high], arr.A[i]];
return i;
}
let arr = { A/* POINTER */: [33, 22, 88, 23, 45, 0, 44, 11] };
let res = QuickSort(arr, 0, arr.A.length - 1);
console.log(res);
Result is [0, 11, 22, 23, 33, 44, 45, 88]
But its not stable; so I checked the other answers and the Idea of #6502 was interesting to me that "two items do not have to be the same" to be distinguishable.
Well, I have a solution in my mind, but it is not optimal. We can keep the indexes of the items in a separate array. Memory consumption will almost double in this idea.
arr.A => Array of numbers
arr.I => Indexes related to each item of A
influencer => This should be a very very small number; I want to use this as a factor to be able to distinguish between similar items.
So we can change the partition like this:
let Partition = (arr, low, high) => {
let pivot = arr.A[high];
let index = arr.I[high];
let i = low;
for (let j = low; j <= high; j++) {
if (arr.A[j] + (arr.I[j] * influencer) < pivot + (index * influencer)) {
[arr.A[i], arr.A[j]] = [arr.A[j], arr.A[i]];
[arr.I[i], arr.I[j]] = [arr.I[j], arr.I[i]];
i++;
}
}
[arr.A[i], arr.A[high]] = [arr.A[high], arr.A[i]];
[arr.I[i], arr.I[high]] = [arr.I[high], arr.I[i]];
return i;
}
let influencer = 0.0000001;
let arr = {
I/* INDEXES */: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
A/* POINTER */: [33, 22, 88, 33, 23, 45, 33, 89, 44, 11]
};
let res = QuickSort(arr, 0, arr.A.length - 1);
console.log(res);
Result:
I: [19, 11, 14, 10, 13, 16, 18, 15, 12, 17],
A: [11, 22, 23, 33, 33, 33, 44, 45, 88, 89]
More compact and easy to understand quicksort implementation
const quicksort = arr =>
arr.length <= 1
? arr
: [
...quicksort(arr.slice(1).filter((el) => el < arr[0])),
arr[0],
...quicksort(arr.slice(1).filter((el) => el >= arr[0])),
];
try my solution
const quickSort = (arr) => {
// base case
if(arr.length < 2) return arr;
// recurisve case
// pick a random pivot
let pivotIndex = Math.floor(Math.random() * arr.length);
let pivot = arr[pivotIndex];
let left = [];
let right = [];
// make array of the elements less than pivot and greater than it
for(let i = 0; i < arr.length; i++) {
if(i === pivotIndex) {
continue;
}
if(arr[i] < pivot) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
// call the recursive case again
return quickSort(left).concat([pivot], quickSort(right));
}
when testing this
quickSort([7, 5, 3, 2, 8, 1, 5]) // returns [[1, 2, 3, 5, 5, 7, 8]]
This is it !!!
function typeCheck(a, b){
if(typeof a === typeof b){
return true;
}else{
return false;
}
}
function qSort(arr){
if(arr.length === 0){
return [];
}
var leftArr = [];
var rightArr = [];
var pivot = arr[0];
for(var i = 1; i < arr.length; i++){
if(typeCheck(arr[i], parseInt(0))){
if(arr[i] < pivot){
leftArr.push(arr[i]);
}else { rightArr.push(arr[i]) }
}else{
throw new Error("All must be integers");
}
}
return qSort(leftArr).concat(pivot, qSort(rightArr));
}
var test = [];
for(var i = 0; i < 10; i++){
test[i] = Math.floor(Math.random() * 100 + 2);
}
console.log(test);
console.log(qSort(test));
Slim version:
function swap(arr,a,b){
let temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
return 1
}
function qS(arr, first, last){
if(first > last) return
let p = first
for(let i = p; i < last; i++)
if(arr[i] < arr[last])
p += swap(arr, i, p)
swap(arr, p, last)
qS(arr, first, p - 1)
qS(arr, p + 1, last)
}
Tested with random values Arrays, and seems to be always faster than Array.sort()
quickSort = (array, left, right) => {
if (left >= right) {
return;
}
const pivot = array[Math.trunc((left + right) / 2)];
const index = partition(array, left, right, pivot);
quickSort(array, left, index - 1);
quickSort(array, index, right);
}
partition = (array, left, right, pivot) => {
while (left <= right) {
while (array[left] < pivot) {
left++;
}
while (array[right] > pivot) {
right--;
}
if (left <= right) {
swap(array, left, right);
left++;
right--;
}
}
return left;
}
swap = (array, left, right) => {
let temp = array[left];
array[left] = array[right];
array[right] = temp;
}
let array = [1, 5, 2, 3, 5, 766, 64, 7678, 21, 567];
quickSort(array, 0, array.length - 1);
console.log('final Array: ', array);
A Fastest implementation
const quickSort = array =>
(function qsort(arr, start, end) {
if (start >= end) return arr;
let swapPos = start;
for (let i = start; i <= end; i++) {
if (arr[i] <= arr[end]) {
[arr[swapPos], arr[i]] = [arr[i], arr[swapPos]];
swapPos++;
}
}
qsort(arr, start, --swapPos - 1);
qsort(arr, swapPos + 1, end);
return arr;
})(Array.from(array), 0, array.length - 1);
Quicksort using ES6, filter and spread operation.
We establish a base case that 0 or 1 elements in an array are already sorted. Then we establish an inductive case that if quicksort works for 0 or 1 elements, it can work for an array of size 2. We then divide and conquer until and recursively call our function until we reach our base case in the call stack to get our desired result.
O(n log n)
const quick_sort = array => {
if (array.length < 2) return array; // base case: arrays with 0 or 1 elements are already "sorted"
const pivot = array[0]; // recursive case;
const slicedArr = array.slice(1);
const left = slicedArr.filter(val => val <= pivot); // sub array of all elements less than pivot
const right = slicedArr.filter(val => val > pivot); // sub array of all elements greater than pivot
return [...quick_sort(left), pivot, ...quick_sort(right)];
}
const quicksort = (arr)=>{
const length = Math.ceil(arr.length/2);
const pivot = arr[length];
let newcondition=false;
for(i=0;i<length;i++){
if(arr[i]>arr[i+1]){
[arr[i], arr[i+1]] = [arr[i+1], arr[i]]
newcondition =true
}
}
for(i=arr.length;i>length-1;i--){
if(arr[i]>arr[i+1]){
[arr[i], arr[i+1]] = [arr[i+1], arr[i]]
newcondition =true
}
}
return newcondition? quicksort(arr) :arr
}
const t1 = performance.now();
const t2 = performance.now();
console.log(t2-t1);
console.log(quicksort([3, 2, 4, 9, 1, 0, 8, 7]));
const quicksort = (arr)=>{
if (arr.length < 2) return arr;
const pivot = arr[0];
const left = [];
const right = [];
arr.shift();
arr.forEach(number => {
(number<pivot) ? left.push(number) : right.push(number);
});
return ([...quicksort(left), pivot, ...quicksort(right)]);
}
console.log(quicksort([6, 23, 29, 4, 12, 3, 0, 97]));
How about this non-mutating functional QuickSort:
const quicksort = (arr, comp, iArr = arr) => {
if (arr.length < 2) {
return arr;
}
const isInitial = arr.length === iArr.length;
const arrIndexes = isInitial ? Object.keys(arr) : arr;
const compF = typeof comp === 'function'
? comp : (left, right) => left < right ? -1 : right < left ? 1 : 0;
const [pivotIndex, ...indexesSansPivot] = arrIndexes;
const indexSortReducer = isLeftOfPivot => [
(acc, index) => isLeftOfPivot === (compF(iArr[index], iArr[pivotIndex]) === -1)
? acc.concat(index) : acc,
[]
];
const ret = quicksort(indexesSansPivot.reduce(...indexSortReducer(true)), compF, iArr)
.concat(pivotIndex)
.concat(quicksort(indexesSansPivot.reduce(...indexSortReducer(false)), compF, iArr));
return isInitial ? ret.reduce((acc, index) => acc.concat([arr[index]]), []) : ret;
};
As a bonus, it supports optional comparing function which enables sorting of array of objects per property/properties, and doesn't get slower if dealing with larger values/objects.
First quick sorts original array keys, then returns sorted copy of original array.

Categories

Resources