Write a program to take a one-dimensional array of N elements and split it in half . Later, sort the first half in ascending order and the second half in descending order.
The solution of performing two operations on two halves in a single array is explained in C language as follows -
The logic of ascending sorting of the first half 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 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 the array into two halves and print accordingly is as follows-
for (i=0; i<b; ++i) printf ("%d ",number[i]);
for(i=b;i<n;i++) printf("%d ",number[i]);
The following is for a single array Two halves of a C program that performs two operations in -
Live Demonstration
#include<stdio.h> void main(){ int i,j,a,n,b,number[30]; printf ("Enter the value of N</p><p>"); scanf ("%d", &n); b = n/2; printf ("Enter the numbers </p><p>"); 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</p><p>"); printf (" arranged in asc</p><p>"); for (i=0; i<b; ++i) printf ("%d ",number[i]); printf("</p><p>The 2nd half Numbers</p><p>"); printf("order arranged in desc.order</p><p>"); for(i=b;i<n;i++) printf("%d ",number[i]); }
When the above program is executed, the following results are produced -
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
The above is the detailed content of C program to perform two halves of an operation on a single array. For more information, please follow other related articles on the PHP Chinese website!