Could anyone please help me.
- Partition Algorithm:
-pivot = pick a random element out of the array A -swap the pivot with the last element of A
small_count = 0 for each element x of array A except the last if x < pivot swap x with A[small_count] add 1 to small_count
swap A[small_count] with the last element of A
Example Run:
Array after picking 4 as pivot and swapping with last pivot = 4, ^ indicates current array element in for loop.
7 6 5 2 3 8 1 9 4 small_count = 0 ^ next element
7 6 5 2 3 8 1 9 4 small_count = 0 ^ next element
7 6 5 2 3 8 1 9 4 small_count = 0 ^ next element
7 6 5 2 3 8 1 9 4 small_count = 0 ^ swap A[0] with 2, add 1 to small_count, next element
2 6 5 7 3 8 1 9 4 small_count = 1 ^ swap A[1] with 3, add 1 to small_count, next element
2 3 5 7 6 8 1 9 4 small_count = 2 ^ next element
2 3 5 7 6 8 1 9 4 small_count = 2 ^ swap A[2] with 1, add 1 to small_count,
next element 2 3 1 7 6 8 5 9 4 small_count = 3 ^ next element 2 3 1 7 6 8 5 9 4 small_count = 3 ^ swap A[small_count] with last element
2 3 1 4 6 8 5 9 7 small_count = 3
Now elements 0 to small_count - 1 are < pivot elements from small_count on are >= pivot
Aucun commentaire:
Enregistrer un commentaire