Understanding Quick Sort Algorithm: Step-by-Step in JavaScript ??

Understanding Quick Sort Algorithm: Step-by-Step in JavaScript ??

Quick Sort is a sorting algorithm based on the Dividea and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array.

  1. Choose a Pivot: Select an element from the array as the pivot. The choice of pivot can vary (e.g., first element, last element, random element, or median).
  2. Partition the Array: Rearrange the array around the pivot. After partitioning, all elements smaller than the pivot will be on its left, and all elements greater than the pivot will be on its right. The pivot is then in its correct position, and we obtain the index of the pivot.
  3. Recursively Call: Recursively apply the same process to the two partitioned sub-arrays (left and right of the pivot).
  4. Base Case: The recursion stops when there is only one element left in the sub-array, as a single element is already sorted.

function partition(arr, low, high) {
  let pivot = arr[high];

  let i = low - 1;

  for (let j = low; j <= high - 1; j++) {
    if (arr[j] < pivot) {
      i++;
      swap(arr, i, j);
    }
  }

  swap(arr, i + 1, high);
  return i + 1;
}

function swap(arr, i, j) {
  let temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}

function quickSort(arr, low, high) {
  if (low < high) {
    let pi = partition(arr, low, high);

    quickSort(arr, low, pi - 1);
    quickSort(arr, pi + 1, high);
  }
}

const arr = [64, 25, 12, 22, 11];
console.log("Original Array:", arr);
quickSort(arr, 0, arr.length - 1);
console.log("Sorted Array:", arr);        

要查看或添加评论,请登录

Harshit Pandey的更多文章

社区洞察

其他会员也浏览了