W
W
WhiteBachelor2018-10-09 23:04:59
JavaScript
WhiteBachelor, 2018-10-09 23:04:59

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

1 answer(s)
J
jcmvbkbc, 2018-10-09
@WhiteBachelor

for (b = sortArray.length; b != 1; b--){
      int1 = sortArray[b];

What do you think?

Error in indexing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question