how to sort an array

How to Sort an Array

If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are bubble sort and quicksort.

Bubble Sort

Bubble sort is a simple algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order.

function bubbleSort(arr) {
  var len = arr.length;
  for (var i = 0; i < len; i++) {
    for (var j = 0; j < len - 1; j++) {
      if (arr[j] > arr[j+1]) {
        var temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
  return arr;

var myArray = [3, 2, 1, 5, 4];

In the example above, we define a function called bubbleSort that takes an array as its parameter. We then declare a variable called len which holds the length of the array. We then loop through the array twice. The outer loop goes from 0 to len-1, and the inner loop goes from 0 to len-2. This is because we are comparing adjacent elements, so we don't want to go out of bounds. If the current element is greater than the next element, we swap them. We then return the sorted array.


Quicksort is a more complex algorithm that works by partitioning the array into two sub-arrays, one containing elements smaller than a chosen pivot and the other containing elements greater than the pivot. The algorithm then recursively sorts the sub-arrays.

function quickSort(arr) {
  if (arr.length <= 1) {
    return arr;
  var pivot = arr[0];
  var left = [];
  var right = [];
  for (var i = 1; i < arr.length; i++) {
    if (arr[i] < pivot) {
    } else {
  return quickSort(left).concat(pivot, quickSort(right));

var myArray = [3, 2, 1, 5, 4];

In the example above, we define a function called quickSort that takes an array as its parameter. We then check if the length of the array is less than or equal to 1. If it is, we return the array as is. If not, we choose the first element as the pivot and create two empty arrays called left and right. We then loop through the array and push elements smaller than the pivot into the left array and elements greater than or equal to the pivot into the right array. We then recursively call quickSort on the left and right arrays and concatenate them along with the pivot to get our sorted array.


Both bubble sort and quicksort are effective sorting algorithms, but quicksort is generally faster and more efficient. However, bubble sort is easier to understand and implement for small arrays. It's important to choose the sorting algorithm that best fits your needs and the size of your array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]