javascript - Sort an array containing numbers using a 'for' loop

Javascript - Sort an array containing numbers using a 'for' loop

To sort an array containing numbers using a for loop in JavaScript, you can implement a simple sorting algorithm such as bubble sort or selection sort. Here's an example using bubble sort, which is straightforward and easy to understand:

Example: Bubble Sort Implementation

function bubbleSort(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]) { // Swap elements let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } // Example usage: let numbers = [5, 3, 8, 2, 1, 4]; console.log("Before sorting:", numbers); // Sorting the array using bubble sort bubbleSort(numbers); console.log("After sorting:", numbers); 

Explanation

  1. Bubble Sort Algorithm:

    • Outer Loop (i): Iterates through the array from the start to the second last element. After each pass, the largest unsorted element is placed at its correct position.
    • Inner Loop (j): Compares adjacent elements and swaps them if they are in the wrong order (ascending in this case).
  2. Swapping Elements:

    • If arr[j] > arr[j + 1], swap arr[j] and arr[j + 1].
  3. Example Usage:

    • Define an array numbers.
    • Call bubbleSort(numbers) to sort the array.
    • Print the sorted array.

Alternative Sorting Algorithms

  • Selection Sort: Similar conceptually to bubble sort but typically has better performance.
  • Insertion Sort: Builds the sorted array one item at a time, inserting each new element into its correct position.

Considerations

  • Efficiency: Bubble sort has a time complexity of O(n^2), which may not be efficient for large arrays. Consider using more efficient sorting algorithms like quicksort or mergesort for larger datasets.
  • In-Place Sorting: Bubble sort sorts the array in-place, meaning it modifies the original array rather than creating a new one.

Using a for loop for sorting arrays in JavaScript helps understand basic sorting principles and algorithms. For production use or larger datasets, consider leveraging built-in sorting methods (Array.prototype.sort()) or more efficient algorithms depending on your specific requirements.

Examples

  1. JavaScript - Sort an array of numbers in ascending order using a 'for' loop

    • Description: Implement a simple bubble sort algorithm using a 'for' loop to sort an array of numbers in ascending order.
    • Code Implementation:
      const numbers = [5, 3, 8, 1, 4]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [1, 3, 4, 5, 8] 
    • Explanation: This code uses a nested 'for' loop with a bubble sort algorithm to sort the numbers array in ascending order.
  2. JavaScript - Sort an array of numbers in descending order using a 'for' loop

    • Description: Sort an array of numbers in descending order using a 'for' loop and a bubble sort algorithm.
    • Code Implementation:
      const numbers = [5, 3, 8, 1, 4]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (numbers[j] < numbers[j + 1]) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [8, 5, 4, 3, 1] 
    • Explanation: This code sorts the numbers array in descending order by modifying the comparison condition in the bubble sort.
  3. JavaScript - Sort an array of numbers excluding zeros using a 'for' loop

    • Description: Sort an array of numbers excluding zeros using a 'for' loop.
    • Code Implementation:
      const numbers = [5, 3, 0, 8, 0, 1, 4]; const n = numbers.length; // Remove zeros const filteredNumbers = numbers.filter(num => num !== 0); // Bubble sort without zeros for (let i = 0; i < filteredNumbers.length - 1; i++) { for (let j = 0; j < filteredNumbers.length - i - 1; j++) { if (filteredNumbers[j] > filteredNumbers[j + 1]) { // Swap elements let temp = filteredNumbers[j]; filteredNumbers[j] = filteredNumbers[j + 1]; filteredNumbers[j + 1] = temp; } } } console.log(filteredNumbers); // Output: [1, 3, 4, 5, 8] 
    • Explanation: This code first filters out zeros from the numbers array and then sorts the non-zero elements using a bubble sort.
  4. JavaScript - Sort an array of numbers with negative values using a 'for' loop

    • Description: Sort an array of numbers that may include negative values using a 'for' loop.
    • Code Implementation:
      const numbers = [5, -3, 8, -1, 4]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [-3, -1, 4, 5, 8] 
    • Explanation: This code sorts the numbers array with both positive and negative values using a bubble sort.
  5. JavaScript - Sort an array of floating-point numbers using a 'for' loop

    • Description: Sort an array of floating-point numbers using a 'for' loop.
    • Code Implementation:
      const numbers = [5.2, 3.1, 8.7, 1.5, 4.9]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [1.5, 3.1, 4.9, 5.2, 8.7] 
    • Explanation: This code sorts the numbers array containing floating-point numbers using a bubble sort.
  6. JavaScript - Sort an array of numbers with duplicate values using a 'for' loop

    • Description: Sort an array of numbers that may contain duplicate values using a 'for' loop.
    • Code Implementation:
      const numbers = [5, 3, 8, 1, 5, 4]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [1, 3, 4, 5, 5, 8] 
    • Explanation: This code sorts the numbers array with duplicate values using a bubble sort.
  7. JavaScript - Sort an array of numbers using a custom sorting criteria with a 'for' loop

    • Description: Sort an array of numbers using a custom sorting criteria (e.g., absolute value) using a 'for' loop.
    • Code Implementation:
      const numbers = [-5, 3, 8, -1, 4]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (Math.abs(numbers[j]) > Math.abs(numbers[j + 1])) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [-1, 3, 4, -5, 8] 
    • Explanation: This code sorts the numbers array based on the absolute value of each number using a bubble sort.
  8. JavaScript - Sort an array of numbers with NaN values using a 'for' loop

    • Description: Sort an array of numbers that may include NaN values using a 'for' loop.
    • Code Implementation:
      const numbers = [5, NaN, 8, 1, NaN, 4]; const n = numbers.length; for (let i = 0; i < n - 1; i++) { for (let j = 0; j < n - i - 1; j++) { if (isNaN(numbers[j])) { // Move NaN values to the end let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } else if (numbers[j] > numbers[j + 1]) { // Swap elements let temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers); // Output: [1, 4, 5, 8, NaN, NaN] 
    • Explanation: This code sorts the numbers array while handling NaN values by moving them to the end using a bubble sort.

More Tags

base-class devise jql adal amp-html opera photo-upload applescript jquery-select2-4 pascals-triangle

More Programming Questions

More Stoichiometry Calculators

More Dog Calculators

More Genetics Calculators

More Entertainment Anecdotes Calculators