Skip to content

Instantly share code, notes, and snippets.

@marioluan
Created May 18, 2013 19:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marioluan/5605583 to your computer and use it in GitHub Desktop.
Save marioluan/5605583 to your computer and use it in GitHub Desktop.
Lista de algoritmos úteis em javascript: quicksort,...
function partition( array, left, right ) {
var pivot = array[Math.floor((left + right)/2)],
i = left,
j = right;
while ( i <= j ) {
while ( array[i] < pivot ) {
i++;
}
while ( array[j] > pivot ) {
j--;
}
if ( i <= j ) {
swap(array, i, j);
i++;
j--;
}
}
return i;
}
function swap( array, leftIndex, rightIndex ) {
var left = array[leftIndex],
right = array[rightIndex];
array[leftIndex] = right;
array[rightIndex] = left;
}
function quickSort( array, left, right ) {
var index;
if (array.length > 1) {
index = partition(array, left, right);
if (left < index - 1) {
quickSort(array, left, index - 1);
}
if (index < right) {
quickSort(array, index, right);
}
}
return array;
}
var array = [4,2,6,5,3,9] || ['mario','luan', 'santos', 'de', 'souza'];
var result = quickSort(array, 0, array.length - 1);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment