Home > Mobile >  Display first even and then odd elements in a C array
Display first even and then odd elements in a C array

Time:07-27

I'm a C newb. I need to insert numbers to an array and then display first the odd numbers and then the even numbers in a single array. I've managed to create two separate arrays with the odd and even numbers but now I don't know how to sort them and put them back in a single array. I need your help to understand how to do this with basic C knowledge, so no advanced functions. Here's my code:

#include <iostream>
using namespace std;

int main()
{

    int N{ 0 }, vector[100], even[100], odd[100], unify[100], i{ 0 }, j{ 0 }, k{ 0 };

    cout << "Add the dimension: " << endl;
    cin >> N;
    cout << "Add the elements: " << endl;

    for (int i = 0; i < N; i  ) {

        cout << "v[" << i << "]=" << endl;
        cin >> vector[i];
    }

    for (i = 0; i < N; i  ) {
        if (vector[i] % 2 == 0) {
            even[j] = vector[i];
            j  ;
        }
        else if (vector[i] % 2 != 0) {
            odd[k] = vector[i];
            k  ;
        }
    }

    cout << "even elements are :" << endl;

    for (i = 0; i < j; i  ) {
        cout << " " << even[i] << " ";
        cout << endl;
    }

    cout << "Odd elements are :" << endl;

    for (i = 0; i < k; i  ) {
        cout << " " << odd[i] << " ";
        cout << endl;
    }

    return 0;
}

CodePudding user response:

If you don't need to store the values then you can simply run through the elements and print the odd and the even values to different stringstreams, then print the streams at the end:

#include <sstream>
#include <stddef.h>
#include <iostream>

int main () {

  std::stringstream oddStr;
  std::stringstream evenStr;

  static constexpr size_t vecSize{100};

  int vec[vecSize] = {10, 5, 7, /*other elements...*/ };

  for(size_t vecIndex = 0; vecIndex < vecSize;   vecIndex) {
    if(vec[vecIndex] % 2 == 0) {
      evenStr << vec[vecIndex] << " ";
    } else {
      oddStr << vec[vecIndex] << " ";
    }
  }

  std::cout << "Even elements are:" << evenStr.rdbuf() << std::endl;
  std::cout << "Odd elements are:" << oddStr.rdbuf() << std::endl;
}

Storing and sorting the elements are always expensive.

CodePudding user response:

Basically, it would be better to sort them first.

#include <iostream>

using namespace std;

int main()
{
    int numbers[5];
    int mergedArrays[5];
    int evenNumbers[5];
    int oddNumbers[5];
    
    for(int i=0;i<5;i  ){
        cin>>numbers[i];
    }
    
    int temp=numbers[0];
    //bubble sort
    for(int i = 0; i<5; i  ) 
    {
       for(int j = i 1; j<5; j  )
       {
          if(numbers[j] < numbers[i]) 
          {
             temp = numbers[i];
             numbers[i] = numbers[j];
             numbers[j] = temp;
          }
       }
   
    }
    
    int nEvens=0;
    int nOdds=0;

    for(int i = 0; i<5; i  ) 
    {
      
       if(numbers[i]%2==0)
       {
           
           evenNumbers[nEvens]=numbers[i];
           nEvens  ;
          
       }
       else if(numbers[i]%2!=0)
       {
           oddNumbers[nOdds]=numbers[i];
           nOdds  ;
        
       }
    }
    
    
 
    
    int lastIndex=0;
    //copy evens
    
    for(int i = 0; i<nEvens; i  ) 
    {
      
       mergedArrays[i]=evenNumbers[i];
       lastIndex=i;
    }
    
 
    
    //copy odds
    for(int i =lastIndex; i<nOdds; i  ) 
    {
      
         mergedArrays[i]=oddNumbers[i];
    }

    return 0;
}

CodePudding user response:

If you don't care about order other than that odd values must precede even values then you can partition your array in O(n) with a single scan.

Below is a sample of how this is done. Note that I neither expect you to understand, nor use, the generator code in this code example that populates a 30-element native array with random values in the range [1..99] using the <random> library. That isn't important. What is important part is the partition algorithm, which is noted within comment braces. The point of that algorithm is to (a) rearrange the elements so odd values precede even values, and (b) calculate the breaking-point where odd values finish and even values start.

Once the partitioning is complete you know how many odd values you have (mid) and how many even values you have (N-mid), and can access them accordingly within the only array needed to do all of this.

The Code

#include <iostream>
#include <utility>
#include <random>

int main()
{
    static constexpr size_t N = 30;
    int arr[30];

    std::mt19937 rng{ std::random_device{}() };
    std::uniform_int_distribution<> dist(1,99);

    for (size_t i=0; i<N;   i)
    {
        arr[i] = dist(rng);
        std::cout << arr[i] << ' ';
    }
    std::cout << '\n';

    //////////////////////////////
    // THIS ALGORITHM
    size_t mid = 0;
    for (size_t i=0; i<N;   i)
    {
        if (arr[i] % 2)
        {
            int tmp = arr[i];
            arr[i] = arr[mid];
            arr[mid  ] = tmp;
        }
    }
    //////////////////////////////

    std::cout << "Odd:  ";
    for (size_t i=0; i<mid;   i)
        std::cout << arr[i] << ' ';
    std::cout << '\n';

    std::cout << "Even: ";
    for (size_t i=mid; i<N;   i)
        std::cout << arr[i] << ' ';
    std::cout << '\n';

    return 0;
}

Output (varies, obviously)

50 5 94 69 14 95 79 46 89 91 13 27 43 29 53 90 76 17 18 53 74 24 52 40 33 30 44 30 50 69 
Odd:  5 69 95 79 89 91 13 27 43 29 53 17 53 33 69 
Even: 90 76 46 18 14 74 24 52 40 94 30 44 30 50 50 

CodePudding user response:

You can use Bubble Sort Algorithm to sort odd and even and insert them into single array like this:

//Bubble Sort

 void bubbleSort(int arr[], int n)
    {
        int i, j;
        for (i = 0; i < n - 1; i  )
      
            // Last i elements are already 
            // in place
            for (j = 0; j < n - i - 1; j  )
                if (arr[j] > arr[j   1])
                    swap(arr[j], arr[j   1]);
    }
  

// Insert In array

int result[100];
for (int i = 0; i < k; i  )
{result[i] = odd[i];}
for (int i = 0; i < j; i  )
{result[i k] = even[i];}
  • Related