Skip to content

JavaScript sort algorithm for Array | Code

  • by

Which algorithm does the JavaScript Array.sort() function use?

Answer: The ECMAScript standard does not specify which sort algorithm is to be used. Indeed, different browsers feature different sort algorithms. For example, Mozilla/Firefox’s sort() is not stable (in the sorting sense of the word) when sorting a map. IE’s sort() is stable.

JavaScript sort algorithm for Array code

Bubble sort algorithm for JavaScript array sort implementation.

<!DOCTYPE html>
<html>
<body>
	
	<script>
		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;
		}
		console.log(bubbleSort([7,5,2,4,3,9,0])); 
		console.log(bubbleSort([9,7,5,4,3,1])); 
		console.log(bubbleSort([1,2,3,4,5,6])); 

	</script>

</body>
</html>

Output:

JavaScript sort algorithm for Array implementation

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *