Created
May 18, 2013 19:52
-
-
Save marioplumbarius/5605583 to your computer and use it in GitHub Desktop.
Lista de algoritmos úteis em javascript: quicksort,...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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