14

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:

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

1 回答 1

38

这里有一个冒泡排序函数供大家参考,但如前所述,排序算法有很多种。

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

于 2013-04-26T19:16:10.977 回答