Sorting arrays using for loop in Javascript

前端 未结 6 1038
灰色年华
灰色年华 2021-01-15 16:36

Is it possible to sort arrays in ascending/descending order using the for loop JavaScript?

I\'ve been learning JS going through a few practice quest

6条回答
  •  遥遥无期
    2021-01-15 17:07

    I was actually working on manually sorting javascript arrays with for loops today. While the code below does assume you're feeding it arrays (e.g, does not check for types), here was a solution I was able to get using for loops only, no built-in sorting methods and no new array creation:

    Sorting Greatest to Least

    function sortGreatest(arr) {
      // manually sort array from largest to smallest:
      // loop forwards through array:
      for (let i = 0; i < arr.length; i++) {
        // loop through the array, moving forwards:
        // note in loop below we set `j = i` so we move on after finding greatest value:
        for (let j = i; j < arr.length; j++) {
          if (arr[i] < arr[j]) {
            let temp = arr[i]; // store original value for swapping
            arr[i] = arr[j]; // set original value position to greater value
            arr[j] = temp; // set greater value position to original value
          };
        };
      };
      return arr;
    };
    
    console.log(sortGreatest([10,9,1000,12,-11,3]));
    // => [ 1000, 12, 10, 9, 3, -11 ]
    

    Sorting Least to Greatest

    function sortLeast(arr) {
      // manually sort array from smallest to largest:
      // loop through array backwards:
      for (let i = arr.length-1; i >= 0; i--) {
        // loop again through the array, moving backwards:
        for (let j = i; j >= 0; j--) {
          if (arr[i] < arr[j]) {
            let temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
          };
        };
      };
      return arr;
    };
    console.log(sortLeast([10,9,1000,12,-11,3]));
    // => [ -11, 3, 9, 10, 12, 1000 ]
    

提交回复
热议问题