Answers for "sort integers by middle digit"

C
0

sort integers by middle digit

/*The program must accept N integers as the input. Each integer contains an odd number of digits. The
program must sort the integers based on the middle digit. If two or more integers have the same middle
digit, then the program must sort those integers in ascending order. */
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int middleDigit(int n)
{
    int len=(int)log10(n)+1;
    return (int)(n/pow(10,len/2))%10;
}
int main()
{
   int n;
   scanf("%d",&n);
   int arr[n];
   for(int i=0;i<n;i++)
      scanf("%d",&arr[i]);
   for(int i=0;i<n;i++)
   {
       for(int j=i+1;j<n;j++)
       {
           int a=middleDigit(arr[i]),b=middleDigit(arr[j]);
           if(a>b)
           {
              int temp=arr[i];
              arr[i]=arr[j];
              arr[j]=temp;
           }
           if(a==b&&arr[i]>arr[j])
           {
               int temp=arr[i];
               arr[i]=arr[j];
               arr[j]=temp;
           }
       }
       printf("%d ",arr[i]);
   }
}
/*******************INPUT AND OUTPUT*****************
INPUT:
5 
82315 40215 70051 56103 20201

OUTPUT:
70051 56103 20201 40215 82315 

INPUT:
6
77344 572 994 583 130 7193942

OUTPUT:
130 77344 7193942 572 583 994 
*****************************************************/
Posted by: Guest on August-26-2021

Code answers related to "C"

Browse Popular Code Answers by Language