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

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

Give an efficient 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
  1. D Ghosh
    December 2, 2014 at 6:17 am

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

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: