Contact Learn C
Copy

Program 288: Odd Even Sorting in C

Program 288: Odd Even Sorting in C

#include<stdio.h>
main()
{
 int i,flag,temp,size;
 printf("Enter number of elements in array\n");
 scanf("%d",&size);
 int a[size];
 printf("Enter Elements of Array for Odd Even Sort\n");
 for(i=0;i<size;i++)
 {
  scanf("%d",&a[i]);
 }
 do{
  flag=0;
  //For Even Sort
  for(i=0;i<size-1;i+=2)
  {
   //Swapping
   if(a[i]>a[i+1])
   {
    temp=a[i];
    a[i]=a[i+1];
    a[i+1]=temp;
        flag=1;
   }
  }
  //For Odd Sort
  for(i=1;i<size-1;i+=2)
  {
   //Swapping
   if(a[i]>a[i+1])
   {
    temp=a[i];
    a[i]=a[i+1];
    a[i+1]=temp;
        flag=1;
   }
  }
 }while(flag);
 
 printf("Array after Sorting\n");
 for(i=0;i<size;i++)
 {
  printf("%d ",a[i]);
 }
 printf("\n");
}
Odd Even Sort for Step by Step Execution output
#include<stdio.h>
void printArray(int a[],int size);
main()
{
 int i,flag,temp,size,count=0,even,odd;
 printf("Enter number of elements in array\n");
 scanf("%d",&size);
 int a[size];
 printf("Enter Elements of Array for Odd Even Sort\n");
 for(i=0;i<size;i++)
 {
  scanf("%d",&a[i]);
 }
 do{
  flag=0;
  count++;
  even=0;
  odd=0;
  //For Odd Sort
  for(i=1;i<size-1;i+=2)
  {
   //Swapping
   if(a[i]>a[i+1])
   {
    temp=a[i];
    a[i]=a[i+1];
    a[i+1]=temp;
        flag=1;
        odd=1;
   }
  }
  if(odd==1)
  {
   printf("%d.Array after Odd Sort\n",count);
       printArray(a,size);
  }
  
  //For Even Sort
  for(i=0;i<size-1;i+=2)
  {
   //Swapping
   if(a[i]>a[i+1])
   {
    temp=a[i];
    a[i]=a[i+1];
    a[i+1]=temp;
        flag=1;
        even=1;
   }
  }
  if(even==1)
  {
   printf("%d.Array after Even Sort\n",count);
        printArray(a,size);
  }
  
  
 }while(flag);
 
 printf("\nArray after Final Sorting\n");
 printArray(a,size);
 printf("\n");
}

void printArray(int a[],int size)
{
 int i;
 for(i=0;i<size;i++)
 {
  printf("%d ",a[i]);
 }
 printf("\n");
}
Explanation:

Algorithm Explanation
Odd Even Sorting in C Explanation


Output:

Odd Even Sorting in C
Odd Even Sort

Odd Even Sort for Step by Step Execution output
Odd Even Sort for Step by Step Execution output

Odd Even Sort for Step by Step Execution output
Odd Even Sort for Step by Step Execution output




Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide