Advertisement
nathanwailes

Partition algorithm

May 18th, 2024 (edited)
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. """ Below is the partition algorithm commonly used in the QuickSort and QuickSelect algorithms. This function partitions the array in place and returns the index where the pivot element is placed. Elements smaller than or equal to the pivot are placed on the left, and elements greater than the pivot are placed on the right.
  2.  
  3. the things I would expect people would be most likely to mess up are:
  4. - you're incrementing up to the element *right before* the last one.
  5. - you're checking if the current element is less than *or equal to* the pivot value.
  6. """
  7.  
  8. def partition(arr, l=None, r=None):
  9.     if l is None:
  10.         l, r = 0, len(arr)-1
  11.     pivot_starting_index = r
  12.     pivot_value = arr[pivot_starting_index]
  13.     pivot_final_index = l
  14.     for j in range(l, r):
  15.         if arr[j] <= pivot_value:
  16.             arr[pivot_final_index], arr[j] = arr[j], arr[pivot_final_index]
  17.             pivot_final_index += 1
  18.     arr[pivot_final_index], arr[pivot_starting_index] = arr[pivot_starting_index], arr[pivot_final_index]
  19.     return pivot_final_index
  20.  
  21. arr = [10, 7, 8, 9, 1, 5]
  22. print(partition(arr), arr)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement