Answer the question
In order to leave comments, you need to log in
Bubble sort fails. What is the problem?
Decided to learn algorithms. Started with bubble sort. Logically, everything is clear, but for some reason the algorithm does not work. The essence of the program. With HTML comes the number of numeric values in the array. Next, an array is created with the given number of variables. Each is assigned a random value by the Math.random() method. An array is returned and sent to the sort function. The array is definitely issued, everything was done correctly here (I'm not an optimization pro, if anything), I checked it. But sorting doesn't work. What is the problem?
Here is the code of that non-working algorithm:
function bubbleSort(sortArray){
for (i = 0; i != sortArray.length - 1; i++){
for (b = sortArray.length; b != 1; b--){
int1 = sortArray[b];
int2 = sortArray[b - 1];
if (int2 > int1){
sortArray[b] = int2;
sortArray[b - 1] = int1;
}
}
}
return sortArray;
}
function getRandomArray(){
quantity = document.getElementById('input_quantity').value;
sortableArray = new Array();
for (i = 0; i != quantity; i++){
sortableArray.splice(i, 0, Math.round(Math.random() * 100));
}
document.getElementById('result').innerHTML = bubbleSort(sortableArray);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question