Arrange all even numbers at top and all odd numbers at bottom of an array
C program to arrange all even numbers at top and all odd numbers at bottom of an array.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void read_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:",i+1);
scanf("%d",&a[i]);
}
}
void print_array(int a[MAX], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Element %d\t:%d\n",i+1,a[i]);
}
}
void segregate_evenodd(int arr[MAX], int n)
{
int left, right, temp;
left = 0;
right = n-1;
while(left < right)
{
while(arr[left]%2 == 0 && left<right)
{
left++;
}
while(arr[right]%2 == 1 && left<right)
{
right--;
}
if(left < right)
{
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
void main()
{
int arr[MAX];
int n;
printf("Enter the number of elements in the array\t:");
scanf("%d",&n);
printf("Enter the elements of the array\n");
read_array(arr, n);
segregate_evenodd(arr, n);
printf("\nModified array is\n");
print_array(arr, n);
getch();
}
Output
Enter the number of elements in the array :9
Enter the elements of the array
Element 1 :12
Element 2 :23
Element 3 :34
Element 4 :45
Element 5 :56
Element 6 :67
Element 7 :78
Element 8 :89
Element 9 :90
Modified array is
Element 1 :12
Element 2 :90
Element 3 :34
Element 4 :78
Element 5 :56
Element 6 :67
Element 7 :45
Element 8 :89
Element 9 :23