2014-02-11

posted Mar 11, 2014, 2:23 PM by Samuel Konstantinovich   [ updated Mar 11, 2014, 2:23 PM ]
Quick Select:

Take any array of integers:
{5,6,2,3,4,10,7,8,9,1,2};    //Sorted would be: {1,2,2,3,4,5,6,7,8,9,10}    

partition around a random number like the number at index 6, which is 7:
5 is less than 7 so we put it on the left side (we could put everything in a new array to make it easier)
[5                                ]
6 is less so left side
[5 6                             ]
2 is less... so are 3 and 4.
[5 6 2 3 4               ]
10 is too big so we put on right side
[5 6 2 3 4             10]
Since we are up to index 6, the 7 is left alone and we go to the 8 which goes to the end, so does the 9:
[5 6 2 3 4            9 8 10]
Then the 1 and 2 go to the beginning:
[5 6 2 3 4 1 2     9 8 10]
We ran out of values, so we put the 7 in the right place:
[5 6 2 3 4 1 2 7 9 8 10]  //notice that the 7 is in the correct slot. The same slot it would be in if it were sorted.

This is the partition step that we talked about in class, and we can do it in place instead of making a copy!!!

More on this tomorrow.
Comments