C program to sort an array in descending order

Write a C program to read elements in an array and sort elements of the array in descending order. Read unsorted integer values in array and sort them in descending order.

Example:
If the elements of array are: 20, 2, 10, 6, 52, 31, 0, 45, 79, 40
Array sorted in descending order: 79, 52, 45, 40, 31, 20, 10, 6, 2, 0

Required knowledge:

Basic C programming, If else, For loop, Array

Algorithm:

Here we will use basic algorithm to sort arrays in descending order:
Step 1: Read elements in array.
Step 2: Set i=0
Step 3: Set j=i+1
Step 4: If array[i] < array[j] then swap value of array[i] and array[j].
Step 5: Set j=j+1
Step 6: Repeat Step 4-5 till j<n (Where n is the size of the array)
Step 7: Set i=i+1
Step 8: Repeat Step 3-7 till i<n

Program:

/**
 * C program to sort elements of array in descending order
 */

#include <stdio.h>

int main()
{
    int arr[100];
    int size, i, j, temp;

    /*
     * Read size of array and elements in array
     */
    printf("Enter size of array: ");
    scanf("%d", &size);

    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /*
     * Array sorting code
     */
    for(i=0; i<size; i++)
    {
        for(j=i+1; j<size; j++)
        {
            /*
             * If there is a smaller element towards left of the array then swap it.
             */
            if(arr[i] < arr[j])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }

    /*
     * Prints the sorted array
     */
    printf("\nElements of array in sorted descending order: ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", arr[i]);
    }

    return 0;
} 
Output
X
_
Enter size of array: 10
Enter elements in array: 20 2 10 6 52 31 0 45 79 40

Elements of array in sorted descending order: 79      52      45      40      31      20      10      6      2      0

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment