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);
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.
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 />"; } ?>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With