Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // QUICKSORT IMPLEMENTATION
- function swap(items, leftIndex, rightIndex){
- let temp = items[leftIndex];
- items[leftIndex] = items[rightIndex];
- items[rightIndex] = temp;
- }
- function partition(items, left, right) {
- let 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) {
- let 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;
- }
- let arr = [1,4,2,6,8,3,1,23,44,44,44];
- console.log(quickSort(arr, 0, arr.length-1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement