Rearranging positive and negative numbers in an array is a common programming problem, typically solved in two distinct methods. Each method has its advantages depending on whether maintaining the order of appearance of the elements is required. Let’s explore both approaches in detail, along with examples and algorithms.
This approach focuses on moving all negative numbers to the beginning of the array and positive numbers to the end without preserving the order of elements.
# Function to rearrange array elements
def rearrange_without_order(arr):
j = 0 # Pointer for the next negative element
for i in range(len(arr)):
if arr[i] < 0:
arr[i], arr[j] = arr[j], arr[i]
j += 1
return arr
# Test case
arr = [1, -1, 2, -2, 3, -3]
print("Rearranged array:", rearrange_without_order(arr))
[1, -1, 2, -2, 3, -3]
[-1, -2, -3, 1, 2, 3]
This method is efficient but does not maintain the order of appearance of elements.
This approach rearranges the array while maintaining the order of appearance of elements. Negative numbers are moved to the beginning, and positive numbers follow.
# Function to rearrange array elements
def rearrange_with_order(arr):
for i in range(1, len(arr)):
key = arr[i]
if key < 0:
j = i - 1
while j >= 0 and arr[j] > 0:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# Test case
arr = [1, -1, 2, -2, 3, -3]
print("Rearranged array:", rearrange_with_order(arr))
[1, -1, 2, -2, 3, -3]
[-1, -2, -3, 1, 2, 3]
This method preserves the order of appearance but is less efficient compared to Method 1.
Conclusion
By understanding and implementing these methods, you can efficiently solve problems involving rearrangement of numbers in arrays. Experiment with the code examples to deepen your comprehension.
CLICK HERE TO KNOW MORE OUR PROGRAM!