Skip to content

JavaScript sort array of numbers without sort function | Example code

  • by

You can use the Bubble sort algorithm to sort an array of numbers without the sort function in JavaScript. There are many different sorting algorithms.

JavaScript sorts an array of numbers without the sort function

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
   function bubbleSort(array) {
    var done = false;
    while (!done) {
      done = true;
      for (var i = 1; i < array.length; i += 1) {
        if (array[i - 1] > array[i]) {
          done = false;
          var tmp = array[i - 1];
          array[i - 1] = array[i];
          array[i] = tmp;
        }
      }
    }

    return array;
  }

  var numbers = [12, 10, 15, 11, 14, 13, 16];
  bubbleSort(numbers);
  console.log(numbers);
</script>
</body>
</html> 

Output:

JavaScript sort array of numbers without sort function

If you want to sort a string in javascript without using a built-in method, just by using for’s and comparisons like ‘a’ > ‘b’.

Use the Below program, which produces the expected output from your program using selection sort.

swap and replace functions work fine.

function sort(str) {
    var sorted = str;
    //Selection sort
    for (var i = 0; i < str.length; i++) {
        for(var j = i + 1; j < str.length - 1; j++) {   
            if (str[i] < str[j]) {
                str = swap(str, i, j)
            }
        }
    }
    return str;
}

console.log(sort("zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa"));
//output: aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz

Do comment if you have any doubts or suggestions on this JS sort array code.

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 *