Suppose we've got an array with negative and positive numbers; it might be helpful to segregate its positive and negative elements. We can sort the array by moving the negative elements to one side. It doesn't yield an efficient solution.
The illustration below uses the following array: [-3, 2, -1, 5, 7, 3, -6, 8, 4], and depicts how a possible algorithm would move all the negative elements to one side of the array efficiently.
The code snippet below provides the algorithm used in the illustration above. A single array traversal is performed, and the index of the array's first positive element is stored throughout. If an element is positive, the traversal continues, but if it is negative, it's swapped with the array's first positive element.
Note: To run the following code, provide input for the array in the form of just integers separated with a space (without commas or brackets).
For example, enter [-3, 5, 1, -6, 4] as:
def shift_negatives(arr) :first_positive = 0for i in range(len(arr)):if arr[i] < 0:temp = arr[i]arr[i] = arr[first_positive]arr[first_positive]= tempfirst_positive += 1return arrarr = input().split()arr = [int(i) for i in arr]print("Original Array:", arr)rearranged_array = shift_negatives(arr)print("Rearranged Array:", rearranged_array)
Enter the input below
The algorithm operates with the following properties:
shift_negatives()
that takes the original array, arr
, and shifts its negative elements to one side.first_positive
function to store the index of the array's first positive elementfirst_positive
. If the current element is positive, we move to the next element.arr
is returned.Free Resources