Question

Consider an array of length n containing positive and negative integers in random order. Write C++...

Consider an array of length n containing positive and negative integers in random order. Write C++ code that rearranges the integers so that the negative integers appear before the positive integers. Your solution should use

  1. O(n2) operations

  2. O(n) operations

0 0
Add a comment Improve this question Transcribed image text
Answer #1

a)

#include <iostream>

using namespace std;

void printArray(int arr[], int n)

{

  for (int i = 0; i < n; i++)

    cout << arr[i] << " ";

  cout << endl;

}

void rearrange(int arr[], int n)

{

  int key, j;

  for (int i = 1; i < n; i++) {

    key = arr[i];

    if (key > 0)

      continue;

    j = i - 1;

    while (j >= 0 && arr[j] > 0) {

      arr[j + 1] = arr[j];

      j = j - 1;

    }

    arr[j + 1] = key;

  }

}

int main()

{

  int arr[] = {1, -6, 11, 18, -6, -18, -9, 11, 18, -4 };

  int n = sizeof(arr) / sizeof(arr[0]);

  rearrange(arr, n);

  printArray(arr, n);

  return 0;

}

1 #include <iostream> using namespace std; > clang++-7 -pthread -o main main.cpp ./main -6 -6 -18 -9 -4 1 11 18 11 18 4 void

b)

#include <iostream>

using namespace std;

void rearrange(int arr[], int n)

{

  int j = 0;

  for (int i = 0; i < n; i++) {

    if (arr[i] < 0) {

      if (i != j)

        swap(arr[i], arr[j]);

      j++;

    }

  }

}

void printArray(int arr[], int n)

{

  for (int i = 0; i < n; i++)

    cout << arr[i] << " ";

}

int main()

{

  int arr[] = {1, -6, 11, 18, -6, -18, -9, 11, 18, -4 };

  int n = sizeof(arr) / sizeof(arr[0]);

  rearrange(arr, n);

  printArray(arr, n);

  return 0;

}

1 #include <iostream> using namespace std; ? clang++-7 -pthread -o main main.cpp > ./main -6 -6 -18 -9 -4 11 18 11 18 1 | 4 v

Add a comment
Know the answer?
Add Answer to:
Consider an array of length n containing positive and negative integers in random order. Write C++...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT