Question -
Given an array A[], write a function that segregates even and odd numbers. The functions should put all even numbers first, and then odd numbers.
Note - ordre doesn't matter.
Example -
Input :arr[] = {1, 2, 3, 4, 5, 6}
Output : {2, 4, 6, 1, 3, 5}
Approach -
we start from starting point , if we got any odd number then we swap this by ending element and decrease ending index else increase starting index.
Implementation -
#include<iostream>
using namespace std;
void separate(int arr[],int n)
{
int left=0,right=n-1;
while(left<right){
if(arr[left]%2!=0){
swap(arr[left],arr[right]);
right--;
}
else
left++;
}
}
int main()
{
int n;
cout<<"Enter the number of the elements : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
separate(arr,n);
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
Time complexity - O(n)
Comments
Post a Comment