如何获得切换按钮以从下降到上升来回切换数组?

时间:2015-11-18 02:19:27

标签: javascript html arrays sorting

我正在使用bubbleSort,我可以让数组从原始顺序切换到降序,但是我无法让它从下降回到升序。我应该只复制bubbleSort代码并翻转大于/小于标志吗?任何帮助表示赞赏!

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;
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

首先,你需要一个切换来告诉你要走哪条路。

var isAscending = false;

然后在for-statement里面的bubbleSort函数中,在if语句之上。

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

然后将if语句替换为:

if (sortComparison)

最后,完成排序后,您可以切换变量:

isAscending = !isAscending;

尽管如此,我建议使用切换变量,而只是使用sort()和reverse()。

https://jsfiddle.net/ytcax0qc/