Last active
October 19, 2016 14:49
-
-
Save simonwoo/f0f9ed12d8843ac1724a5b518647e717 to your computer and use it in GitHub Desktop.
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
| // One pointer | |
| var partition1 = function(array, start, end) { | |
| if(start === end) { | |
| return; | |
| } | |
| // Choose the first element as pivot | |
| var pivot = array[start]; | |
| // last position which is smaller than pivot | |
| var small = start; | |
| for(var index = start + 1; index <= end; index++) { | |
| if(array[index] < pivot) { | |
| small++; | |
| array[small] = [array[index], array[index]=array[small]][0]; | |
| } | |
| } | |
| array[small] = [array[start], array[start]=array[small]][0]; | |
| } | |
| var partition2 = function(array, start, end) { | |
| // 2 pointers | |
| if(start === end) { | |
| return; | |
| } | |
| var pivot = array[start]; | |
| var i = start + 1; | |
| var j = end; | |
| while(index <= j) { | |
| while(array[i] < pivot && i < j) { | |
| i++; | |
| } | |
| while(array[j] >= pivot && i < j) { | |
| j--; | |
| } | |
| array[i] = [array[j], array[j]=array[i]][0]; | |
| i++; | |
| j--; | |
| } | |
| array[i] = [array[start], array[i]=array[start]][0]; | |
| } | |
| var partition3 = function(array, target, start, end) { | |
| // 3 ways partition | |
| if(start === end) { | |
| return; | |
| } | |
| var i = start, | |
| j = end | |
| index = start; | |
| while(i < j) { | |
| if(array[index] < target) { | |
| if(i != index) { | |
| array[i] = [array[index], array[index]=array[i]][0]; | |
| } | |
| i++; | |
| } else if(array[index] > target){ | |
| if(j != index) { | |
| array[j] = [array[index], array[index]=array[j]][0]; | |
| } | |
| j--; | |
| } | |
| index++; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment