Sort even and odd elements separately in an array
C program to sort even and odd elements separately in 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 sort(int arr[MAX], int start, int end)
{
int i, j, temp;
for(i=start;i<end;i++)
{
for(j=i+1;j<end;j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void main()
{
int arr[MAX], arr1[MAX], arr2[MAX];
int n, i, pivot;
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);
pivot = 0;
i = 0;
while(arr[i]%2 == 0)
{
pivot++;
i++;
}
sort(arr, 0, pivot);
sort(arr, pivot, 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 :34
Element 3 :21
Element 4 :56
Element 5 :43
Element 6 :78
Element 7 :54
Element 8 :21
Element 9 :89
Modified array is
Element 1 :12
Element 2 :34
Element 3 :54
Element 4 :56
Element 5 :78
Element 6 :21
Element 7 :21
Element 8 :43
Element 9 :89