sort array from smallest to biggest in javascript wihout the sort function in javascript

Here is an example algorithm to sort an array of numbers from smallest to largest without using the built-in sort() function in JavaScript:

index.tsx
function sortArray(arr) {
  // Loop through each element in array
  for (let i = 0; i < arr.length; i++) {
    // Loop through remaining elements to find minimum value
    for (let j = i + 1; j < arr.length; j++) {
      // If current element is greater than next element, swap them
      if (arr[i] > arr[j]) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}
421 chars
16 lines

This function uses a nested loop to compare each element in the array to the remaining elements and swap their positions if the current element is larger than the next element. By repeating this process, the smallest element in the array eventually "bubbles" to the beginning, and the array becomes sorted from smallest to largest.

Example usage:

index.tsx
let nums = [9, 5, 2, 7, 1, 10];
console.log(sortArray(nums)); // [1, 2, 5, 7, 9, 10]
85 chars
3 lines

gistlibby LogSnag