Pages

Friday, 15 December 2017

Sort Array using pointer

Question : Write a function in ‘C’, using pointers for the array of elements, for sorting the elements.
Solution : 


#include<stdio.h>
#include<conio.h>
void sort(int*);
void main()
{

     int ar[5],i;
     clrscr();
     for(i=0;i<5;i++)
     {
          printf("Enter number>> ");
          scanf("%d",&ar[i]);
     }
     printf("\nUnsorted array\n");
     for(i=0;i<5;i++)
          printf("\t%d",ar[i]);
     sort(ar);
     printf("\nsorted array\n");
     for(i=0;i<5;i++)
          printf("\t%d",ar[i]);

     getch();

}
void sort(int *p)
{
     int i,j,tmp;
     for(i=0;i<5;i++)
     {
          for(j=0;j<5-i-1;j++)
          {
              if(p[j]>p[j+1])
              {
                   tmp=p[j];
                   p[j]=p[j+1];
                   p[j+1]=tmp;
              }
          }
     }


}

No comments:

Post a Comment