Thursday 14 December 2017

Sort an Array using pointer

Q : What do you mean by a pointer variable? Write a function in ‘C’, using pointers for the array of elements, for sorting the elements.

Solution : 

Pointer

A pointer is a special type of variable which hold physical address of a non pointer variable.Symbol * is used to make a pointer variable. Programmer can change a variable value from another location with the help of pointer. Call reference is an example of pointer , in which  a variable physical address pass to a function and any change made inside of function direct effect actual value of passed variable due to pointer.

& (Address operator ) is used to assign address of a variable to pointer. * (Indirection Operator) is used to access value of variable point by pointer.

Pointer Diagram


200,300 is physical address

Syntax :

Data_type *var_name

e.g.
void main()
{
     int *ptr;
     int x=10;
     ptr=&x;
     printf("\nValue of x through pointer %d",*ptr);
}



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