From d6f641ec34c4e19560d9e21571d35188731da115 Mon Sep 17 00:00:00 2001 From: King Josaphat Chewa Date: Thu, 23 May 2019 00:14:04 +0100 Subject: [PATCH] Update index.md (#32810) --- .../sorting-algorithms/quick-sort/index.md | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/guide/english/algorithms/sorting-algorithms/quick-sort/index.md b/guide/english/algorithms/sorting-algorithms/quick-sort/index.md index 83c9894c64..31cd898cb3 100644 --- a/guide/english/algorithms/sorting-algorithms/quick-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/quick-sort/index.md @@ -15,64 +15,64 @@ The steps involved in Quick Sort are: ### Implementation in JavaScript: ```javascript -const arr = [6, 2, 5, 3, 8, 7, 1, 4] +const arr = [6, 2, 5, 3, 8, 7, 1, 4]; const quickSort = (arr, start, end) => { if(start < end) { // You can learn about how the pivot value is derived in the comments below - let pivot = partition(arr, start, end) + let pivot = partition(arr, start, end); // Make sure to read the below comments to understand why pivot - 1 and pivot + 1 are used // These are the recursive calls to quickSort - quickSort(arr, start, pivot - 1) - quickSort(arr, pivot + 1, end) + quickSort(arr, start, pivot - 1); + quickSort(arr, pivot + 1, end); } } const partition = (arr, start, end) => { - let pivot = end + let pivot = end; // Set i to start - 1 so that it can access the first index in the event that the value at arr[0] is greater than arr[pivot] // Succeeding comments will expound upon the above comment - let i = start - 1 - let j = start + let i = start - 1, + j = start; // Increment j up to the index preceding the pivot while (j < pivot) { // If the value is greater than the pivot increment j if (arr[j] > arr[pivot]) { - j++ + j++; } // When the value at arr[j] is less than the pivot: // increment i (arr[i] will be a value greater than arr[pivot]) and swap the value at arr[i] and arr[j] else { - i++ - swap(arr, j, i) - j++ + i++; + swap(arr, j, i); + j++; } } //The value at arr[i + 1] will be greater than the value of arr[pivot] - swap(arr, i + 1, pivot) + swap(arr, i + 1, pivot); //You return i + 1, as the values to the left of it are less than arr[i+1], and values to the right are greater than arr[i + 1] // As such, when the recursive quicksorts are called, the new sub arrays will not include this the previously used pivot value - return i + 1 + return i + 1; } const swap = (arr, firstIndex, secondIndex) => { - let temp = arr[firstIndex] - arr[firstIndex] = arr[secondIndex] - arr[secondIndex] = temp + let temp = arr[firstIndex]; + arr[firstIndex] = arr[secondIndex]; + arr[secondIndex] = temp; } -quickSort(arr, 0, arr.length - 1) -console.log(arr) +quickSort(arr, 0, arr.length - 1); +console.log(arr); ``` ### Implementation in C