DEV Community

Discussion on: QuickSort Algorithm in Javascript

Collapse
 
rrdlpl profile image
R

Sure,

class QuickSort {
  public sort(array: number[], left: number, right: number): number[] {
    if (array.length <= 1) {
      return array;
    }

    let index = this.partition(array, left, right);

    if (left < index - 1) {
      this.sort(array, left, index - 1);
    }

    if (index < right) {
      this.sort(array, index, right);
    }

    return array; 
  }
  private partition(array: number[], left: number, right: number): number {
    const pivot = array[Math.floor(right + left / 2)];
    let i = left;
    let j = right;


    while (i <= j) {
      while (array[i] < pivot) {
        i++;
      }
      while (array[j] > pivot) {
        j--;
      }

      if (i <= j) {
        this.swap(array, i, j);
        console.log(`swapping ${i} ${j}`, array);
        i++;
        j--;
      }
    }

    return i;
  }

  private swap(array: number[], i: number, j: number) {
    const aux = array[i];
    array[i] = array[j];
    array[j] = aux;
  }
}

const q = new QuickSort();
const array = [5, 6, 3, 7, 1, 8, 9];

console.log(q.sort(array, 0, array.length - 1));

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
shubhamtiwari909 profile image
Shubham Tiwari

So this one is memory efficient