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.
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.
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.
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).
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.
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:
pop
and shift
), improves the performance considerably.l
and L
before the loop , prevents the need of being calculated repeatedly in each iteration.I've prepared some PERFORMANCE TESTS, with some of the proposed algorithms : Original Array(10 items) and Big Array(1000 items)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With