Skip to content

Instantly share code, notes, and snippets.

@radhar
Created July 16, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radhar/aa215bd16c04c00e6babd5ca7325e9ab to your computer and use it in GitHub Desktop.
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.
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