Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array with numbers without sort() method [closed]

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);
like image 885
Dali Avatar asked Apr 26 '13 18:04

Dali


People also ask

Can you sort an array of numbers?

The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.

How can I sort an array in PHP without sort method?

php function sortArray() { $inputArray = array(8, 2, 7, 4, 5); $outArray = array(); for($x=1; $x<=100; $x++) { if (in_array($x, $inputArray)) { array_push($outArray, $x); } } return $outArray; } $sortArray = sortArray(); foreach ($sortArray as $value) { echo $value . "<br />"; } ?>


1 Answers

Here is a Bubble sort function 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);
like image 136
Xotic750 Avatar answered Oct 18 '22 10:10

Xotic750