Created
July 16, 2020 15:21
-
-
Save radhar/aa215bd16c04c00e6babd5ca7325e9ab to your computer and use it in GitHub Desktop.
There is an array of numbers from 1 to 100 which are not in order. Sort the array in O(N) complexity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
There is an array of numbers from 1 to 100 which are not in order. Sort the array in O(N) complexity. | |
// implemented the function to sort any given array | |
function sortValues(arrofUnsorted){ | |
var minimum = arrofUnsorted[0]; | |
var maximun = arrofUnsorted[0]; | |
var arrSorted = []; | |
var temp; | |
// finding the max value in the given arrofUnsorted array | |
for (i=0; i<arrofUnsorted.length; i++) | |
{ | |
if (maximun < arrofUnsorted[i]){ | |
maximun = arrofUnsorted[i]; | |
} | |
} | |
// find each time minmum value in the arrofUnsorted/original array to replace it with "sort" and add the new minimum to the arrSorted array | |
for (var i=0; i<arrofUnsorted.length; i++){ | |
// fetch next minimum value. | |
for (var j=0; j<arrofUnsorted.length; j++){ | |
// check for elements whose value is not "sort" | |
if (arrofUnsorted[j] != "sort"){ | |
if (minimum > arrofUnsorted[j]){ | |
minimum = arrofUnsorted[j]; | |
temp = j; | |
} | |
} | |
} | |
arrSorted[i] = minimum ; | |
arrofUnsorted[temp] = "sort"; | |
minimum = maximun; | |
} | |
return arrSorted; | |
} | |
var finalArrayAfterSort = sortValues([2,1,4,20,8,30,5,7]); | |
console.log(finalArrayAfterSort); | |
Output: [1,2,4,5,7,8,20,30] | |
Example: | |
var finalArrayAfterSort = sortValues([99,2,4,70,8,30,1,29]); | |
console.log(finalArrayAfterSort); | |
Output: [1,2,4,8,29,30,70,99] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment