Sort The Array In Descending Order Using For Loop In Javascript

Sort The Array In Descending Order Using For Loop In Javascript

4 min read Jun 20, 2024
Sort The Array In Descending Order Using For Loop In Javascript

Sorting an Array in Descending Order using a For Loop in JavaScript

This article will guide you through sorting an array of numbers in descending order using a for loop in JavaScript. While there are built-in methods like sort() that offer a more concise solution, understanding the manual approach using a for loop enhances your understanding of sorting algorithms and provides flexibility for customization.

The Logic

The core idea is to iterate through the array and compare each element with the subsequent ones. If the current element is smaller than the next one, we swap their positions. This process is repeated for each element in the array until the largest element bubbles to the top, and the array is sorted in descending order.

Code Example

function sortDescending(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] < arr[j]) {
        // Swap elements if the current element is smaller than the next
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}

// Example usage:
let numbers = [5, 2, 9, 1, 7];
let sortedNumbers = sortDescending(numbers);
console.log(sortedNumbers); // Output: [9, 7, 5, 2, 1]

Explanation

  1. sortDescending(arr) Function: This function takes an array (arr) as input and returns the sorted array in descending order.

  2. Outer Loop (for (let i = 0; i < arr.length - 1; i++)): This loop iterates through the array from the first element to the second-to-last element. We stop at the second-to-last element because the last element will already be in its correct position after the previous iterations.

  3. Inner Loop (for (let j = i + 1; j < arr.length; j++)): This loop compares the current element (arr[i]) with all the elements after it.

  4. Comparison (if (arr[i] < arr[j])): This condition checks if the current element is smaller than the next element.

  5. Swapping (let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;): If the current element is smaller, we swap the elements to ensure the larger element is moved to the left.

  6. Return Sorted Array: After all iterations, the sortDescending function returns the sorted array.

Key Points

  • The provided code implements the bubble sort algorithm, a simple but often inefficient sorting algorithm.
  • The nested for loop structure allows for pairwise comparisons and swapping.
  • You can modify the comparison operator (<) to achieve ascending order (>).

Remember, for larger datasets, more efficient sorting algorithms like Merge Sort or Quick Sort are generally preferred. However, understanding the manual sorting process using a for loop is valuable for its clarity and flexibility.