javascript 没有 sort() 方法的数字排序数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16243366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:52:34  来源:igfitidea点击:

Sorting array with numbers without sort() method

javascriptarrayssorting

提问by Dali

I'm learning Javascript and I'm stuck with an exercise I found in a tutorial, I think it was learn street.com... I have to sort an array with numbers without using the sort() method. Something like this:

我正在学习 Javascript 并且我坚持在教程中找到的一个练习,我认为它是学习 street.com ......我必须在不使用 sort() 方法的情况下对带有数字的数组进行排序。像这样的东西:

numbers =[12,10,15,11,14,13,16];

I have tried a lot of things since this morning but I can't find how to do this. Anyone can help? I need explanations too, not only the answer!

从今天早上开始,我尝试了很多东西,但我找不到如何做到这一点。任何人都可以帮忙吗?我也需要解释,不仅仅是答案!

Thanks

谢谢

Oh and see what I have at this point:

哦,看看我现在有什么:

function ordre(liste){
var result=[];


for(i=0; i<liste.length; i++){

for(j=0; j<liste.length; j++){
        if(liste[i]>liste[j+1]){

        }
    }

 }

 console.log( result );
}

ordre(nombres);

回答by Xotic750

Here is a Bubble sortfunction for you to reference, but as mentioned there are many different sorting algorithms.

这里有一个冒泡排序函数供您参考,但如前所述,有许多不同的排序算法

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