Program to sort an array elements

0 Suresh Chand June 2, 2021

In this example, We will learn a program sort an array elements. Before that, You must have knowledge in following topics

Download Application: Learn C Programming with Live Compiler

Algorithm

This is the algorithm of this program

Step 1: Start
Step 2: Initialize variables a, i, j, c, temp and n
Step 3: Take input from user and store in n
Step 4: Assign i = 0
Step 5: Repeat this step until i < n
        Take input from user and store in a[i]
        Increase i by 1
Step 6: Assign i = 1 and j = 0
Step 7: REPEAT this step until i < y-1
        REPEAT this step until j < y-i
                IF a[i] > a[j]
                        temp = a[i];
                        a[j] = a[i];
                        a[i] = temp;
                Increase j by 1
        Increase i by 1
Step 8: Assign  i = 0
Step 9: REPEAT this step until i < n
        Print a[i]
Step 10: End

Flowchart

This is the flowchart of this program

Flowchart : Program to sort an array elements

CODE: Program to sort an array elements

Now, We will see the code to sort array elements using for loop.

#include<stdio.h>

void sorting(int *x, int y);

int main()
{
    int a[20], i, c, n;
    
    printf("How many elements to sort: ");
    scanf("%d", &n);

    for(i = 0; i < n; i++)
        scanf("%d", &a[i]);

    sorting(a, n);

    for(i = 0; i <n; i++)
        printf("%d\t", a[i]);
    

    return 0;
}

void sorting(int *x, int y)
{
    int i, j, temp;
    for(i = 1; i <= y-1; i++)
    {
        for(j = 0; j < y-i; j++)
        {
            if(*(x+j) > *(x+j+1))
            {
                temp = *(x+j);
                *(x+j) = *(x+j+1);
                *(x+j+1) = temp;
            }
        }
    }
}

The output of above program is

How many elements to sort: 5
12
45
87
4
3
3       4       12      45      87   
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

Ads Block Detector Powered by codehelppro.com

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System