Sort Array in ascending order in C

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 <stdio.h>
int main()
{
    int num[20];
    int i, j, a, n;
    printf("Enter array limit:\n");
    scanf("%d", &n);
    if (n > 20)
    {
        printf("Array limit out of range!");
        return 0;
    }
    printf("Enter array elements:\n");
    for (i = 0; i < n; ++i)
        scanf("%d", &num[i]);
    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;
            }
        }
    }
    printf("Array sorted in ascending order:\n");
    for (i = 0; i < 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 see

C Programming language
Go Programming language
Linked List Array
Stack Queue
Puzzle Reasoning
Aptitude HTML

 

Previous articleAverage Aptitude Test Paper 1

LEAVE A REPLY

Please enter your comment!
Please enter your name here