alternateSort()

Run Settings
LanguageJavaScript
Language Version
Run Command
/** * @author: K. Lae Kettavong * * @date: 3/04/19 * * @description: Coding challenge, function to generate alternate array from given array and determine if new array is sorted * * You are given an array of integers a. A new array b is generated by rearranging the elements of a in the following way: * * b[0] is equal to a[0]; * b[1] is equal to the last element of a; * b[2] is equal to a[1]; * b[3] is equal to the second-last element of a; * and so on. * Your task is to determine whether the new array b is sorted in strictly ascending order or not. * * Example * * For a = [1, 3, 5, 6, 4, 2], the output should be alternatingSort(a) = true. * * The new array b will look like [1, 2, 3, 4, 5, 6], which is in strictly ascending order, so the answer is true. * * For a = [1, 4, 5, 6, 3], the output should be alternatingSort(a) = false. * * The new array b will look like [1, 3, 4, 6, 5], which is not in strictly ascending order, so the answer is false. * */ const alternateSort = (inputArray) => { if(!Array.isArray(inputArray) || inputArray.length === 0) return false let revArray = [...inputArray].reverse() let newArray = [] let len = Math.ceil(inputArray.length / 2) let ndx = 0 while (ndx < len) { newArray.push(inputArray[ndx]) if( newArray.length < inputArray.length) { newArray.push(revArray[ndx]) } ndx++ } const isSorted = isArraySorted(newArray) console.log(newArray, isSorted) return isSorted } const isArraySorted = (inputArray) => { let ndx = 0 while (ndx < inputArray.length - 1) { if(inputArray[ndx] > inputArray[++ndx]) return false } return true } // O(2n) -> O(n) -> linear time console.log(alternateSort('hello')) console.log(alternateSort(1,2,3)) console.log(alternateSort([])) alternateSort([1, 3, 5, 6, 4, 2]) alternateSort([1, 4, 5, 6, 3]) alternateSort([1]) alternateSort([1, 2]) alternateSort([1, 3, 2]) alternateSort([-89, -47, -38, 39, 82, 87, 40, -9, -41, -68]) alternateSort([-92, -17, 71, 76, 54, -35]) alternateSort([-52, 2, 31, 56, 47, 29, -35]) alternateSort([-97, -51, -8, 25, 44, 70, 98, 77, 68, 31, -5, -36, -80]) alternateSort([-86, -49, -26, -22, 22, 32, 44, 67, 38, 25, 13, -25, -42, -71]) alternateSort([-92, -23, 0, 45, 89, 96, 99, 95, 89, 41, -17, -48]) alternateSort([-37, -31, -8, 88, -10, -33]) alternateSort([-87, -52, 83, 96, 98, 94, 68, -71]) alternateSort([-92, 9, 41, 99, 29, -78]) alternateSort([-91, -84, -67, -44, 9, 70, 88, 37, -11, -67, -72, -87]) alternateSort([-44, -73, -24, 22, 91, 84, 2, -40, -56]) alternateSort([-79, -48, -42, 4, 9, 55, 70, 84, 62, 40, 7, -28, -46, -74]) alternateSort([-27, -81, -7, 21, 33, 52, 23, -6, -10, -71]) alternateSort( [-99, -29, -7, 17, 28, 71, 98, 86, 42, 22, 0, -29, -86]) alternateSort([-86, 93, 4, 27, 49, 74, 74, -70, 60, 41, 14, -44, -80]) alternateSort([42, -80, -72, -25, 18, -94, 99, 49, 37, 10, -45, -76, -87])
Editor Settings
Theme
Key bindings
Full width
Lines