retagged by
410 views
0 votes
0 votes
Consider an array consisting of –ve and +ve numbers. What would be the worst time comparisons an algorithm can take in order to segregate the numbers having same sign altogether i.e all +ve on one side and then all -ve on the other?

a)N-1      b)N      c)N+1     d) (N*(N-1))/2

answer given is a)
retagged by

1 Answer

0 votes
0 votes
Yes, $n-1$ does seem correct in the worst case.

Have a look at this code:

int main(int argc, char const *argv[])
{
    int arr[] = {-12, 11, 0, -5, 6, -7, 5, -3, -6};
    int n = sizeof(arr) / sizeof(arr[0]);

    int i = 0, j = 0;

    while(j < n){
        if(arr[j] < 0) swap(arr[i++], arr[j++]);
        else j++;
    }

    for(int i = 0; i < n; i++) cout << arr[i] << " ";
    return 0;
}

This does what you are looking for in $O(n)$ time.
Answer:

Related questions

0 votes
0 votes
0 answers
1
radha gogia asked Nov 16, 2018
518 views
Answer given is Option A , but here we wil first sort the jobs in order of profit , for each value of deadline scan linearly in the array depending on the value of deadli...
0 votes
0 votes
2 answers
2
Banti Arya asked Jan 27, 2016
1,342 views
0 votes
0 votes
0 answers
3
Sajal Mallick asked Nov 27, 2023
204 views
As we have to select maximal set of “non overlapping” activities. So like job scheduling algo of greedy we can solve it. So according to that complexity must be O(n l...