From d7c556104a200b32da5696bb0bb383887b26a272 Mon Sep 17 00:00:00 2001 From: Gain John <46064597+Dhaxor@users.noreply.github.com> Date: Wed, 16 Sep 2020 22:17:00 +0100 Subject: [PATCH 1/2] Create QuickSort.js Added Quick sort --- SortingAlgorithms/QuickSort.js | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 SortingAlgorithms/QuickSort.js diff --git a/SortingAlgorithms/QuickSort.js b/SortingAlgorithms/QuickSort.js new file mode 100644 index 0000000..975b6bf --- /dev/null +++ b/SortingAlgorithms/QuickSort.js @@ -0,0 +1,42 @@ +var items = [5,3,7,6,2,9]; +function swap(items, leftIndex, rightIndex){ + var temp = items[leftIndex]; + items[leftIndex] = items[rightIndex]; + items[rightIndex] = temp; +} +function partition(items, left, right) { + var pivot = items[Math.floor((right + left) / 2)], //middle element + i = left, //left pointer + j = right; //right pointer + while (i <= j) { + while (items[i] < pivot) { + i++; + } + while (items[j] > pivot) { + j--; + } + if (i <= j) { + swap(items, i, j); //sawpping two elements + i++; + j--; + } + } + return i; +} + +function quickSort(items, left, right) { + var index; + if (items.length > 1) { + index = partition(items, left, right); //index returned from partition + if (left < index - 1) { //more elements on the left side of the pivot + quickSort(items, left, index - 1); + } + if (index < right) { //more elements on the right side of the pivot + quickSort(items, index, right); + } + } + return items; +} +// first call to quick sort +var sortedArray = quickSort(items, 0, items.length - 1); +console.log(sortedArray); //prints [2,3,5,6,7,9] From 0a7a95617eaf5f6d8b92ca18db1fc634156f8fb4 Mon Sep 17 00:00:00 2001 From: Gain John <46064597+Dhaxor@users.noreply.github.com> Date: Thu, 5 Nov 2020 19:32:25 +0100 Subject: [PATCH 2/2] Update QuickSort.js --- SortingAlgorithms/QuickSort.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/SortingAlgorithms/QuickSort.js b/SortingAlgorithms/QuickSort.js index 975b6bf..69db83b 100644 --- a/SortingAlgorithms/QuickSort.js +++ b/SortingAlgorithms/QuickSort.js @@ -1,4 +1,3 @@ -var items = [5,3,7,6,2,9]; function swap(items, leftIndex, rightIndex){ var temp = items[leftIndex]; items[leftIndex] = items[rightIndex]; @@ -37,6 +36,4 @@ function quickSort(items, left, right) { } return items; } -// first call to quick sort -var sortedArray = quickSort(items, 0, items.length - 1); -console.log(sortedArray); //prints [2,3,5,6,7,9] +