Home
> algorithm > [3] Give an eﬃcient algorithm to rearrange an array of n keys so that all the negative keys precede all the nonnegative keys.

## [3] Give an eﬃcient algorithm to rearrange an array of n keys so that all the negative keys precede all the nonnegative keys.

Give an eﬃcient algorithm to rearrange an array of n keys so that all the

negative keys precede all the nonnegative keys.

Solution:

1. Scan through the list from left to right through i .

2. Point the first positive number in the list say it j (initially -1).

3. When List[i] is a negative number and j >-1, swap list[i] & list [j] and increment j by 1

4. When List[i] is a negative number and j == -1, we haven’t get any positive number and go through scanning.

Complexity : O(n)

Advertisements

Categories: algorithm

as i & j so is it not O(n^2)? How it is O(n)?