About Me

My photo
Posting here few basic programs. I prefer using C++. Trying to keep it error free. Feel free to point any of them. Thanks for visiting. You can copy paste code directly from here.

Friday 23 September 2011

/*ASSIGNMENT - 2 DISCRETE STRUCTURES

Sorting


  program for sorting in C using M A and S functions

  M is used to find maximum amongst a list of numbers
  A is used to find greater of 2 numbers and put the bigger number to the Right Hand Side in the list
  S is the sorting function which is used recursively
********************************************************************************************************************/

                                           
                              

                                                                             /* pre-processor directives */ 
#include<stdio.h>
#include<conio.h>

#define size 50                                                 /* helps in changing array size */




int array[size], numberOfValues = 0, temp = 0, n=0, j=0;
                                                               /* variable declaration , these are defined Globally*/

void a()
{
             if(array[j] > array[j+1])               /* here swapping the smaller with bigger number and moving it right*/
             {
                          temp = array[j];
                          array[j] = array [j+1];
                          array[j+1] = temp;
             }
}


void m()                                                      /* m() calls a() */
{
     for(j = 0; j< (n-1); ++j)
     a();
}



void s()                                                             /* and here s calls m() */
{
    if(n != 0)
    {
       
        m();
        n--;
        s();                                                          /* see here s() is called recursively i.e. s() calls s()*/
    }
}




int main()
{
   
    clrscr();
    printf("\n\tNumber of elements...: ");
    scanf("%d", &numberOfValues);
   
    int i;                                                                        
                                                                                                       /* inputs */
   
    for(i = 0; i < numberOfValues; ++i)
    {
            printf("Element no. %3d : ", i+1);
            scanf("%d", &array[i]);
    }
   
    n = numberOfValues;
    s();
   
   
    printf{"\nOUTPUT");
    for(i = 0; i < numberOfValues; ++i)                                              /*output*/
    {
            printf("%d  ", array[i]);
    }
   
   
    getch();
   
    return 0;
}








Sample Output:




   

No comments:

Post a Comment