C program to sort an array in ascending order

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

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

Required knowledge:

Basic C programming, If else, For loop, Array

Algorithm:

Here we will use basic algorithm to sort arrays in ascending 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 ascending 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 right of the array then swap it.
             */
            if(arr[j] < arr[i])
            {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }

    /*
     * Prints the sorted array
     */
    printf("\nElements of array in sorted ascending 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 ascending order: 0      2      6      10      20      31      40      45      52      79

Happy coding ;)


You may also like

Labels: , , ,