i have used a expression to decrement the for loop in javascript and it is not working

43 Views Asked by At

in my shell sort code, i have used a expression to decrement the 1st for loop and it's seems not working that's why my loop runs infinitely, can someone explain why the decrementing expression is not working ?. Here is the Code.....

const shellSort = function (arr) {
  let gap;
  for (gap = Math.floor(arr.length / 2); gap >= 1; Math.floor(gap / 2)) {
    for (let j = gap; j < n; j++) {
      for (let i = j - gap; i >= 0; i - gap) {
        if (arr[i + gap] > arr[i]) break;
        else [arr[i], arr[i + gap]] = [arr[i + gap], arr[i]];
      }
    }
  }
  return arr;
};
1

There are 1 best solutions below

0
Wiktor Zychla On

Both loop steps are incorrect, you can't have just

Math.floor(gap / 2)

because what you mean is

gap = Math.floor(gap / 2)

Same applies to the i loop.

Also, n is undefined there.

Your code corrected

var shellSort = function (arr) {
  let gap;
  for (gap = Math.floor(arr.length / 2); gap >= 1; gap = Math.floor(gap / 2)) {
    for (let j = gap; j < arr.length; j++) {
      for (let i = j - gap; i >= 0; i = i - gap) {
        if (arr[i + gap] > arr[i]) break;
        else [arr[i], arr[i + gap]] = [arr[i + gap], arr[i]];
      }
    }
  }
  return arr;
};