Program to Sort first half in ascending order and second half in descending order in an array in C

Sort an array in ascending and second half in descending order

In this problem, we are required to Sort array ascending and descending order that is to display the first half of the array in ascending order and the remaining half in descending order.

for example if the input array is 1,3,4,2,5,6 then the formatted  array will be 1,2,3,6,5,4 means for 1st half its in ascending order and for second half its in descending order

Sort an array in ascending and second half in descending order
Sort an array in ascending and second half in descending order in C

Algorithm:-

  1. Input size of array.
  2. Store it in some variable say n and a[].
  3. To select each element from array, run an outer loop from 0 to n-1.
  4. Run another inner loop from i + 1 to n – 1 to place newly selected element at its correct position.
  5. Inside inner loop to compare currently selected element with subsequent element and swap two array elements, if not placed at its correct position.

C Program :-

  • In this problem, we are required to display the first half of the array in ascending order and the remaining half in descending order.
#include<stdio.h>
int main ()
{
int i = 0, temp, len, arr[50];
printf ("Enter the length of the array : ");
scanf ("%d", &len);
printf ("Enter the element of the array : ");

for (i = 0; i < len; i++)
{
scanf ("%d", &arr[i]);
}

for (i = 0; i < len - 1; i++)
{
for (int j = i + 1; j < len; j++)
{
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//printing first half of the array
printf ("Sorted Array ");

for (i = 0; i < len / 2; i++)
{
printf ("%d ", arr[i]);
}
//printing second half of the array

for (i = len - 1; i >= len / 2; i--)
{
printf ("%d ", arr[i]);
}
}

Output

Enter the length of the array : 6
Enter the element of the array : 1
5
6
2
3
4
Sorted Array 1 2 3 6 5 4


//2nd test case
Enter the length of the array : 7
Enter the element of the array : 1
7
2
6
3
5
4
Sorted Array 1 2 3 7 6 5 4