Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best algorithm to perform alternate sorting of array using javascript?

Tags:

javascript

The following was my interview question. But I couldn't crack it and even could not think how to get this done.

var arr = [1,4,5,8,3,2,6,9,7,10];

Expected output of alternate sorting:

[10,1,9,2,8,3,7,4,6,5]

What I have tried:
I tried slicing out the Math.max.apply(null,arr) and Math.min.apply(null,arr) alternatively to push into separate empty array. But It was told that the algorithm is not optimal.

like image 890
Prem Avatar asked May 04 '18 04:05

Prem


People also ask

Which algorithm is best for sorting an array?

Quicksort. Quicksort is generally thought of as the most efficient 'general' sorting algorithm, where nothing is known about the inputs to the array, and it's more efficient than insertion sort on large lists.

What is the most efficient sorting algorithm in JavaScript?

Quick Sort Algorithm Quicksort is one of the most efficient ways of sorting elements in computer systems. Similor to merge sort, Quicksort works on the divide and conquer algorithm.

How do you sort an alternate element in an array?

Given an array of integers, print the array in such a way that the first element is first maximum and second element is first minimum and so on. A simple solution is to first print maximum element, then minimum, then second maximum, and so on. Time complexity of this approach is O(n2).

Which algorithm is used in arrays sort JavaScript?

Quicksort. Quicksort applies the divide and conquer technique as well. It works by having a pivot element such that the elements to the left of it are less than it and those to the right are greater than it. The pivot element can be any element in the array.


1 Answers

I would sort the array, and then iterate it, picking values from the begining and the end (inloop calculated offsets), in each iteration. A final check to odd arrays would complete the process.

let a = [1, 4, 5, 8, 3, 2, 6, 9, 7, 10];
a.sort((a, b) => a - b);
let b =[];
    
let l = a.length-1;  // micro optimization
let L = l/2;         // micro optimization
for(var i=0; i<L; i++) b.push( a[l-i] ,a[i] );
if(a.length%2) b.push( a[i] ); // add last item in odd arrays

console.log(b);

Result :

b =  [10, 1, 9, 2, 8, 3, 7, 4, 6, 5]

Algorithm bennefits:

  • Avoiding alterations in the original array (through pop and shift), improves the performance considerably.
  • Precalculating l and L before the loop , prevents the need of being calculated repeatedly in each iteration.
  • A single conditional cheking at the end of the procces, to handle odd arrays, slightly improves the speed.

I've prepared some PERFORMANCE TESTS, with some of the proposed algorithms : Original Array(10 items) and Big Array(1000 items)

like image 157
colxi Avatar answered Oct 25 '22 17:10

colxi