简体   繁体   中英

How do I get a toggle button to toggle an array back and forth from descending to ascending?

I am using bubbleSort, and I can get the array to toggle from its original order to descending, but I am having trouble getting it to go from descending back to ascending. Should I just copy the bubbleSort code and flip the greater than/less than signs? Any help is appreciated!

var myStuff = [];
function myfunctionA() {
  var enteredvalue = document.getElementById("numbers").value;
  // alert(typeof Number(document.getElementById('numbers').value));
  if (enteredvalue == "") {
    alert("Input is not a number");
  } else if (isNaN(enteredvalue)) {
    alert('You need to enter a valid number!');
  }
  var elementExists = false;
  var x = document.getElementById('numbers').value;
  for (var i = 0; i < myStuff.length; i++) {
    if (myStuff[i] == Number(x)) {
      elementExists = true;
    }
  }
  if(elementExists != true) {
    myStuff.push(Number(enteredvalue));
    alert('Thank You for entering a valid number.');
  } else {
    alert('Element is here');
  }
}
function myfunctionB() {
  window.alert(myStuff.length);
}
function myfunctionC() {
  var sum = 0;
  for(var i = 0; i < myStuff.length; i++) {
    sum+=myStuff[i];
  }
  alert(sum);
}
function myfunctionD() {
  if (myStuff.length == 0) {
    alert("already empty");
  } else {
    myStuff = [];
  }
  alert("Array Empty");
}
function myfunctionE() {
  alert(myStuff.join('\n'));
  {
    if (myStuff == []) {
      alert("Enter something into Array")
    }
  }
}

function bubbleSort() {
  var sorted = true;
  var temp;
  while(sorted) {
    sorted = false;
    for(var i = 0; i < myStuff.length-1; i++) {
      if(myStuff[i] < myStuff[i+1]) {
        temp = myStuff[i];
        myStuff[i] = myStuff[i+1];
        myStuff[i+1] = temp;
        sorted = true;
      }
    }
  }
}

First you'll need a toggle to tell which way you are going.

var isAscending = false;

Then in your bubbleSort function inside the for-statement, above the if-statement.

var sortComparison;
if (isAscending) sortComparison = myStuff[i] > myStuff[i];
if (!isAscending) sortComparison = myStuff[i] < myStuff[i];

Then replace your if-statement with:

if (sortComparison)

Finally, once you have finished sorting, you can toggle your variable:

isAscending = !isAscending;

Though, I'd recommend using a toggled variable and simply using sort() and reverse() instead.

https://jsfiddle.net/ytcax0qc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM