005_array in ascending order in c programming

Array in ascending order in C

Problem statement
Given an array, sort in ascending order.

Solution

Use two for loops, Outer for loop for preserving index and the element at that index and inner one to iterate over remaining array.

for (i = 0; i < n; ++i){
   for (j = i + 1; j < n; ++j){
      if (num[i] > num[j]){
         a = num[i];
         num[i] = num[j];
         num[j] = a;
      }
   }
}

 

#include &lt;stdio.h&gt;
int main()
{
    int num[20];
    int i, j, a, n;
    printf("Enter array limit:\n");
    scanf("%d", &amp;n);
    if (n &gt; 20)
    {
        printf("Array limit out of range!");
        return 0;
    }
    printf("Enter array elements:\n");
    for (i = 0; i &lt; n; ++i)
        scanf("%d", &amp;num[i]);
    for (i = 0; i &lt; n; ++i)
    {
        for (j = i + 1; j &lt; n; ++j)
        {
            if (num[i] &gt; num[j])
            {
                a = num[i];
                num[i] = num[j];
                num[j] = a;
            }
        }
    }
    printf("Array sorted in ascending order:\n");
    for (i = 0; i &lt; n; ++i)
    {
        printf("%d\t", num[i]);
    }
    return 0;
}
$ ./a.out
Enter array limit:
7
Enter array elements:
8
7
6
5
4
3
2
Array sorted in ascending order:
2 3 4 5 6 7 8
$ ./a.out
Enter array limit:
2
Enter array elements:
3
4
Array sorted in ascending order:
3 4
$ ./a.out
Enter array limit:
2
Enter array elements:
1
1
Array sorted in ascending order:
1 1
$ ./a.out
Enter array limit:
34
Array limit out of range!
$

If you like the post Sort Array in ascending order in C, please share your feedback!

also read:


HTML DATA STRUCTURE
DBMS REASONING
C PROGRAM APTITUDE
E-LEARNING

 

Previous articleDisplaying Images in HTML
Next articleMove Last Element to Front of a Given Linked List

LEAVE A REPLY

Please enter your comment!
Please enter your name here