• retagged by
681 views
0 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)

1 Answer

0 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:
Position:
Show:

Related questions

0 0 votes
0 0 answers
1.2k
1.2k views
radha gogia asked Nov 16, 2018
1,208 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 0 votes
2 2 answers
2.2k
2.2k views
Banti Arya asked Jan 27, 2016
2,160 views
A set of ' $n$ ' jobs is given. Associated with job $i$ is an integer deadline $d_{1} \geq 0$ and a profit $P_{i}>0$ and each job need to be executed for one unit of time...
2 2 votes
2 2 answers
181
181 views
Shubham Sharma 2 asked Apr 19
181 views
Which of the following is correct order of increasing time complexity of algorithmsTower of Hanoi with $n$ disk.Binary search given $n$ sorted numbers.Heap sort given $n$...
1 1 vote
1 1 answer
414
414 views
Shubham Sharma 2 asked Sep 10, 2025
414 views
Match the LIST-I with LIST-II$\begin{array}{|l|l|l|l|} \hline & \textbf{LIST-I} & & \textbf{LIST-II} \\ & \textbf{Algorithm} & & \textbf{Complexity} \\ \hline \text{A.}...