/*
* Input : A sequence of numbers
* Output : Sorts the given sequence in a way as to get all
* even numbers (in ascending order) followed by all odd
* numbers (in ascending order).
* Method : First, sort the elements using any of the sorting
* technique.Then push all even numbers to the left
* and odd numbers to the right.
*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
// Function Declaration
void sort_even_odd();
int *array,n,i;
printf("Enter the number of elements\n");
scanf("%d",&n);
// Dynamically allocate memory for n elements
array=(int *)calloc(n, sizeof(int));
// Reading values to the list
printf("Enter the elts:");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
// Invoking function sort_even_odd
sort_even_odd(array,n);
//display sorted array
printf("sorted array:");
for(i=0;i<n;i++)
printf("%d ",array[i]);
printf("\n");
return 0;
}
void sort_even_odd(int *arr, int num)
{
int i,j,temp,pos;
// Bubble Sort
for(i=0;i<num;i++) {
for(j=i+1;j<num;j++) {
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
// Pushing all even numbers to the left
j=0;
for(i=0;i<num;i++)
{
if(arr[i]%2==0)
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
j++;
}
}
// Note the end of the even numbers (pos)
for(i=0;i<num;i++)
if(arr[i]%2!=0)
{
pos=i;
break;
}
// Sort all the numbers (odd) from pos till
// end of array
for(i=pos;i<num;i++) {
for(j=i+1;j<num;j++) {
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
Written by Munia Balayil
No comments:
Post a Comment