Skip to content

Commit

Permalink
quicksort.js (HarshCasper#1319)
Browse files Browse the repository at this point in the history
* Create quicksort.js

* Update quicksort.js

* Update README.md

Co-authored-by: Abhinav Anand <[email protected]>
  • Loading branch information
Gaurav-Sadawarti and atarax665 authored Nov 25, 2020
1 parent b05690d commit 84a0d3f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions JavaScript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
- [Bubble Sort](./sort/BubbleSort.js)
- [Insertion Sort](./sort/insertion_sort.js)
- [Sleep Sort](./sort/sleepSort.js)
- [Quick Sort](./sort/quicksort.js)

## Machine Learning

Expand Down
56 changes: 56 additions & 0 deletions JavaScript/sort/quicksort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
What is Quick Sort?
Quick Sort algorithm follows Divide and Conquer approach.
It divides elements into smaller parts based on some condition and
performing the sort operations on those divided smaller parts.
Time Complexity : O(N*logN)
*/

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]

0 comments on commit 84a0d3f

Please sign in to comment.