This blog is under construction

Sunday, 23 June 2013

C program to sort N numbers in ascending order

Write a C program to sort N numbers in ascending order.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int n, *entry, temp, i, j;

        /* get the number of entries from the user */
        printf("Enter the number of entries:");
        scanf("%d", &n);

        entry = (int *)malloc(sizeof (int) * n);

        /* get the values from the user */
        printf("Please enter your inputs:\n");
        for (i = 0; i < n; i++)
                scanf("%d", &entry[i]);

        /* sort data in ascending order */
        for (i = 0; i < n - 1; i++) {
                for (j = i + 1; j < n; j++) {
                        if (entry[i] > entry[j]) {
                                temp = entry[i];
                                entry[i] = entry[j];
                                entry[j] = temp;
                        }
                }
        }

        /* print the sorted data */
        printf("After Sorting:\n");
        for (i = 0; i < n; i++)
                printf("%-3d", entry[i]);
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of entries:10
  Please enter your inputs:
  10 20 15 17 40 30 25 55 45 33
  After Sorting:
  10 15 17 20 25 30 33 40 45 55 



No comments:

Post a Comment