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 ;)


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).

5 comments:

  1. Hello pankaj..please can you help me solve this ex without using another arrays?!!
    Consider an array T of n integers (n constant)
    Write a program to sort the even elements and sort the odd elements of T by ascending order, depending on the min of T : if the min is even, even elements must be sorted first, otherwise, odd elements will start the aray.

    Remark :You cannot sort the whole array and then rearrange it.
    Example :
    T
    0 4 2 1 5 3 6
    T after sorting :
    0 2 4 6 1 3 5

    ReplyDelete