def partition(arr, left, right): """ Its task is do the partition (the array bw the left-right range both inclusive) and return the pivot_index 1. Select a pivot index Randomized for better performance [average O(n log n)] , else O(n2) 2. partition the array over that pivot_index 3. return the pivot_index """ randomize_pivot(arr, left, right) # NOTE : Right now our actual_pivot is at index right future_correct_pivot_index = left # let say actual_pivot_value = arr[right] while left < right: # going till the adjacent element of right if arr[left] < actual_pivot_value: # arr[left], arr[future_correct_pivot_index] = arr[future_correct_pivot_index], arr[left] swap_array_elements(arr, left, future_correct_pivot_index) future_correct_pivot_index += 1 left += 1 # swapping the actual_pivot to its correct_index arr[future_correct_pivot_index], arr[right] = arr[right], arr[ future_correct_pivot_index] return future_correct_pivot_index
def reverse_recursively_helper(arr, left, right): if left >= right: return # traversal complete # swap the two extreme elements swap_array_elements(arr, left, right) # arr[left], arr[right] = arr[right], arr[left] reverse_recursively_helper(arr, left + 1, right - 1)
def reverse_iterative(arr): left, right = 0, len(arr) - 1 while left < right: swap_array_elements( arr, left, right) # arr[left], arr[right] = arr[right], arr[left] left += 1 right -= 1 return arr
def partition_around_0(A, left, right): pivot_value = 0 future_correct_pivot_index = left # as our pivot element external and not in array while left <= right: # Going till the last element and not just to 2nd last Notice if A[left] < pivot_value: # A[left], A[future_correct_pivot_index] = A[future_correct_pivot_index], A[left] swap_array_elements(arr, left, future_correct_pivot_index) future_correct_pivot_index += 1 left += 1
def two_pointer(arr): left = 0 right = len(arr) - 1 while left < right: if arr[left] < 0: # -ve left += 1 # go right if arr[right] >= 0: # +ve right -= 1 # go left if not (not (arr[left] >= 0) or not (arr[right] < 0)): # left is -Ve and right is +Ve swap_array_elements(array, left, right) # A[left], A[right] = A[right], A[left] left += 1 right -= 1
def push_non_negative_unique_integers_to_correct_index(arr): n = len(arr) for i in range(0, n): while arr[i] < n and i != arr[i]: # The condition arr[i]<n, will handle the out of bound scenarios swap_array_elements(arr, i, arr[i]) # Note : arr[i] , arr[arr[i]] = arr[arr[i]] , arr[i] Will Not Work!