Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

quick sort

function swap(arr, leftIndex, rightIndex){
  // swap 2 elements in the array
    var temp = arr[leftIndex];
    arr[leftIndex] = arr[rightIndex];
    arr[rightIndex] = temp;
}
function partition(arr, left, right) {
    var pivot   = arr[Math.floor((right + left) / 2)], //middle element
        i       = left, //left pointer
        j       = right; //right pointer
    while (i <= j) { // while left pointer is smaller than right pointer
        while (arr[i] < pivot) { // move the left pointer to the right
            i++;
        }
        while (arr[j] > pivot) { // move the right pointer to the left
            j--;
        }
        if (i <= j) { //left pointer smaller or equal to right pointer
            swap(arr, i, j); //sawpping two elements
            i++;
            j--;
        }
    }
    return i;
}
// run as quickSort(array, 0, array.length - 1);
function quickSort(arr, left, right) {
    var index;
    if (arr.length > 1) {
        index = partition(arr, left, right); //index returned from partition
        if (left < index - 1) { //more elements on the left side of the pivot
            quickSort(arr, left, index - 1);
        }
        if (index < right) { //more elements on the right side of the pivot
            quickSort(arr, index, right);
        }
    }
    return arr;
}
Source by sorting-algorithms.me #
 
PREVIOUS NEXT
Tagged: #quick #sort
ADD COMMENT
Topic
Name
9+1 =