Answers for "javascript array sort implementation"

2

what is the algorithm for javascript array.sort

function bubbleSort(arr){
   var len = arr.length;
   for (var i = len-1; i>=0; i--){
     for(var j = 1; j<=i; j++){
       if(arr[j-1]>arr[j]){
           var temp = arr[j-1];
           arr[j-1] = arr[j];
           arr[j] = temp;
        }
     }
   }
   return arr;
}
bubbleSort([7,5,2,4,3,9]); //[2, 3, 4, 5, 7, 9]
bubbleSort([9,7,5,4,3,1]); //[1, 3, 4, 5, 7, 9]
bubbleSort([1,2,3,4,5,6]); //[1, 2, 3, 4, 5, 6]
Posted by: Guest on November-30-2019
4

how the sort function works javascript

const unsorted = ['d', 'd', 'h', 'r', 'v', 'z', 'f', 'c', 'g'];
const sorted = unsorted.sort();

console.log(sorted);
//["c", "d", "d", "f", "g", "h", "r", "v", "z"]


const unsortedNums = [45, 56, 3, 3, 4, 6, 7, 45, 1];
const sortedNums = unsortedNums.sort((a, b) => {
	return a - b;
});

console.log(sortedNums);
//[1, 3, 3, 4, 6, 7, 45, 45, 56]
Posted by: Guest on April-07-2020

Code answers related to "javascript array sort implementation"

Browse Popular Code Answers by Language