Skip to main content

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

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...