How to usea for loop in Javascript

The Sort function employs the bubble sort algorithm to arrange array elements in ascending order. It iterates through the array, comparing adjacent elements and swapping them if they are in the wrong order. Variables len, i, and j respectively represent the array length, outer loop index, and inner loop index. temp temporarily holds elements during swapping. The sorted array is returned.

Example: This example shows the implementation of the above-explained approach.

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

const array = [5, 3, 9, 1, 7];
const sortedArray = Sort(array);
console.log("Sorted Array (Ascending):",
    sortedArray);

Output
Sorted Array (Ascending): [ 1, 3, 5, 7, 9 ]

JavaScript Program to Sort the Elements of an Array in Ascending Order

Sorting an array in ascending order means arranging the elements from smallest element to largest element. we will learn to sort an array in ascending order in JavaScript.

These are the following methods:

Table of Content

  • Using the sort method
  • Using a for loop
  • Using Insertion Sort

Similar Reads

Approach 1: Using the sort method

In this approach, A function sortAsc to sort an array in ascending order. The arr parameter represents the input array. It creates a copy of the array using slice() to avoid modifying the original array. The sort() method arranges elements in ascending order based on the return value of the comparison function (a, b) => a – b, subtracting b from a. Finally, it returns the sorted array....

Approach 2: Using a for loop

The Sort function employs the bubble sort algorithm to arrange array elements in ascending order. It iterates through the array, comparing adjacent elements and swapping them if they are in the wrong order. Variables len, i, and j respectively represent the array length, outer loop index, and inner loop index. temp temporarily holds elements during swapping. The sorted array is returned....

Approach 3: Using Insertion Sort

Insertion sort is a simple sorting algorithm that works similarly to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part....

Contact Us