Skip to content

Instantly share code, notes, and snippets.

@d-beloved
Last active December 21, 2020 12:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d-beloved/7316994a4420cea7b508a98b3846ff73 to your computer and use it in GitHub Desktop.
Save d-beloved/7316994a4420cea7b508a98b3846ff73 to your computer and use it in GitHub Desktop.

An array of integers is defined as being in meandering order when the first two elements are the respective largest and smallest elements in the array and the subsequent elements alternate between its next largest and next smallest elements. In other words, the elements are in order of [first_largest, first_smallest, second_largest, second_smallest, ...].

Example

The array [5, 2, 7, 8, -2, 25, 25] sorted normally is [-2, 2, 5, 7, 8, 25, 25]. Sorted in meandering order, it becomes [25, -2, 25, 2, 8, 5, 7]

Function Description

The function takes one parameter, unsorted[n]: the unsorted array

Returns: int[n]: the array sorted in meandering orderj

// this is a crude implementation, kindly share your view on how you would optimize it
function meanderingArray(unsorted) {
// copy the arrays into two different arrays, sort one in descending order and the other in ascending order
let aunsorted = unsorted.slice()
let bunsorted = unsorted.slice()
let sorteddsc = aunsorted.sort((a,b)=> b-a)
let sortedasc = bunsorted.sort((a,b)=> a-b)
let meanderArray = [];
// construct the meanderArray from the two sorted arrays,picking from the arrays simultaneously
for (let i = 0; i < sorteddsc.length; i++) {
meanderArray.push(sorteddsc[i])
if (meanderArray.length === unsorted.length){
return meanderArray
}
meanderArray.push(sortedasc[i])
if (meanderArray.length === unsorted.length){
return meanderArray
}
}
}
let unsorted = [5,2,7,8,-2,25,25]
meanderingArray(unsorted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment