O
O
Old Odessa2017-03-19 17:57:06
JavaScript
Old Odessa, 2017-03-19 17:57:06

What's wrong with my sorting?

I tried to implement qsort and something didn't work. The browser just hangs. I just started learning js, maybe something in the syntax is wrong?

var myArray = [], i, n=10;
for (i=n;i--;){
  myArray[i]=Math.floor(Math.random()*100); 
}
console.log(myArray);
document.write("Input array:<br>");

for (i=n;i--;){
  document.write(myArray[i]);
  if (i!=0){document.write(", ");}
} 
//to swap items 
function swap (array, x, y){
  var z = array[x]; array[x] = array[y]; array[y] = z; 
  return array;
}
//main qsort function 
function qsort (arrayToSort, i, j){
  var left = i; 
  var right = j;
  var pivot = arrayToSort[Math.floor((i+j)/2)];
  while (left<=right){
  	while (arrayToSort[left]>pivot) {
  		left++;
  	}
  	while (arrayToSort[right]<pivot) {
  		right++;
  	}
  	if(left<=right){
  		swap(arrayToSort, left, right);
  		left++;
  		right--;
  	}
  }
  if (i<left){
  	qsort(arrayToSort, i, left);
  }
  if (j<right){
  	qsort(arrayToSort, j, right);
  }
  return arrayToSort; 
}
qsort(myArray,0, myArray.length -1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zakharov Alexander, 2017-03-19
@AlexZaharow

If the browser freezes, then it took this code to execute. Open the debugger and step through the sort. (usually F12).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question