“Jak ręcznie sortować tablicę JavaScript” Kod odpowiedzi

Jak sortować tablicę bez użycia metody sort w JavaScript

function bubbleSort(array) {
  var done = false;
  while (!done) {
    done = true;
    for (var i = 1; i < array.length; i += 1) {
      if (array[i - 1] > array[i]) {
        done = false;
        var tmp = array[i - 1];
        array[i - 1] = array[i];
        array[i] = tmp;
      }
    }
  }

  return array;
}

var numbers = [12, 10, 15, 11, 14, 13, 16];
bubbleSort(numbers);
console.log(numbers);
Smiling Salmon

Jak ręcznie sortować tablicę JavaScript

//This code was written by user Smiling Salmon, full credit goes to them
//(the code is written very neatly and compactly)
//I've added comments to each individual line incase you are a total
//JS noob such as myself, who has no idea how to read this. 
//hopefully you find the following commented lines educational.
var done = false;
   //prevents loop ending before the array is properly sifted through enough times
  function sort (array) {
  while (!done) {
    done = true;
    //this code is set in a way so that the biggest number will always go to the end of the array
    //it does this by checking if the number listed before it in the array is bigger than the current
    //number listed in the array.
    //Therefore, i is set to 1 instead of 0 so that the code is able to check "is the number behind me bigger?"
    for (var i = 1; i < array.length; i += 1) {
      //compares item in list before current item to the current item
      if (array[i - 1] > array[i]) {
        //tells the program to continue looping because there is still a number out of place.
        done = false;
        //tmp is used to temporarily copy the value of the bigger number onto itself
        var tmp = array[i - 1];
        //the bigger number then becomes the current number
        array[i - 1] = array[i];
        //and the current number then becomes the number which was previously before it. (thanks tmp)
        array[i] = tmp;
        //the code will continue to push the bigger numbers to the front until the conditional
        //no longer tells done to equal false, thus ending the looping and sorting the array.
      }
    }
  }
  }
var numbers = [12, 10, 15, 11, 14, 13, 16];
sort(numbers);
console.log(numbers);
obi1baloney

Odpowiedzi podobne do “Jak ręcznie sortować tablicę JavaScript”

Pytania podobne do “Jak ręcznie sortować tablicę JavaScript”

Więcej pokrewnych odpowiedzi na “Jak ręcznie sortować tablicę JavaScript” w JavaScript

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu