Sort n numbers in ascending order using pointers


C program to sort n numbers in ascending order using pointers

  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int i, j, n, tmp, *ptr;
        /* get the number of inputs from the user */
        printf("Enter number of inputs:");
        scanf("%d", &n);

        /* dynamic memory allocation for n elements */
        ptr = (int *)malloc(sizeof(int) * n);

        /* get the inputs from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < n; i++) {
                scanf("%d", ptr + i);
        }

        /* sort the given numbers in ascending order */
        for (i = 0; i < n - 1; i++) {
                for (j = i + 1; j < n; j++) {
                        if (*(ptr + i) > *(ptr + j)) {
                                tmp = *(ptr + i);
                                *(ptr + i) = *(ptr + j);
                                *(ptr + j) = tmp;
                        }
                }
        }

        /* prints the sorted numbers */
        printf("Output:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", *(ptr + i));
        }
        printf("\n");

        /* release the dynamically allocated memory */
        free(ptr);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter number of inputs: 5
  Enter your inputs:
  99  29  34  14  25
  Output:
  14  25  29  34  99

Comments

Popular posts from this blog

Difference between asterisk and ampersand operators in c

kbhit in c