C program to perform operations on two halves’ in a single array

CServer Side ProgrammingProgramming

Problem

Write a program to accept a one-dimensional array of N elements and split into two halves. Later on, sort the first half in an ascending order and the second half into descending order.

Solution

The solution to perform the two operations on two halves’ in a single array in C programming language is explained below −

The logic used to sort the first half in an ascending order is as follows

for (i=0; i<b; ++i){
   for (j=i+1; j<b; ++j){
      if (number[i] > number[j]){
         a = number[i];
         number[i] = number[j];
         number[j] = a;
      }
   }
}

The logic used to sort the second half in the descending order is as follows −

for (i=b; i<n; ++i){
   for (j=i+1; j<n; ++j){
      if (number[i] < number[j]){
         a = number[i];
         number[i] = number[j];
         number[j] = a;
      }
   }
}

The logic used to split an array into two halves and print accordingly is given below −

  • Ascending order first half
for (i=0; i<b; ++i)
printf ("%d ",number[i]);
  • Descending order second half
for(i=b;i<n;i++)
printf("%d ",number[i]);

Example

Following is the C program to perform two operations on two halves’ in a single array

 Live Demo

#include<stdio.h>
void main(){
   int i,j,a,n,b,number[30];
   printf ("Enter the value of N\n");
   scanf ("%d", &n);
   b = n/2;
   printf ("Enter the numbers \n");
   for (i=0; i<n; ++i)
      scanf ("%d",&number[i]);
      for (i=0; i<b; ++i){
         for (j=i+1; j<b; ++j){
            if (number[i] > number[j]){
               a = number[i];
               number[i] = number[j];
               number[j] = a;
         }
      }
   }
   for (i=b; i<n; ++i){
      for (j=i+1; j<n; ++j){
         if (number[i] < number[j]){
            a = number[i];
            number[i] = number[j];
            number[j] = a;
         }
      }
   }
   printf (" The 1st half numbers\n");
   printf (" arranged in asc\n");
   for (i=0; i<b; ++i)
      printf ("%d ",number[i]);
   printf("\nThe 2nd half Numbers\n");
   printf("order arranged in desc.order\n");
   for(i=b;i<n;i++)
      printf("%d ",number[i]);
}

Output

When the above program is executed, it produces the following result −

Enter the value of N

10
Enter the numbers
20
34
23
11
45
56
78
98
76
54
The 1st half numbers
arranged in asc
11 20 23 34 45
The 2nd half Numbers
order arranged in desc.order
98 78 76 56 54
raja
Published on 01-Sep-2021 13:02:26
Advertisements