Wednesday, August 10, 2011

Sorting Techniques in C: Bubble Sort Implementation


Sorting is one of the most common used techniques in business as well any organizations as such. For arranging the database of an employee or student information you would definitely need to use any one of the sorting techniques. 

There many sorting techniques with simple ones being the bubble sort, insertion sort and selection which are used to sort small amount of data, whereas for sorting larger amounts of data you can use Heap, Merge or even Quick sort!

Bubble Sort

This is one of the basic sorting techniques to start of with; all you need to is traverse down the array from the first element to the last one and iterate until the array is completely sorted. 

It is always preferred to have flag which is set on an exchange of two elements in one iteration and if no exchange takes place then the flag is not set as such.

Let us now consider a simple example: 

Let the elements in the array be 3 1 2 4, and you need to sort them in ascending order

First iteration: 1 3 2 4

I and 3 are swapped, since 3 is greater than 1

Second iteration: 1 2 3 4

2 and 3 are swapped, since 3 is greater than 2

Code Snippet:

Let bsort[ ] be an array with n number of elements to be sorted.

// for n number of iteration

for( int i=0 ; i
{
            // to traverse from first element to last element (i.e. n-1 since it is an array)
            for( int j=0 ; j
            {
                        //logic for swapping two numbers
                        if( bsort[ j ] > bsort[ j+1] )
                        {
                                    int temp = bsort[ j+1];
                                   
                                    bsort[ j+1] = bsort [ j ];
                                   
bsort [j] = temp;
                        }
            }
}




Tuesday, February 1, 2011

C Program to Check How Function Calls Are Made Using Stack

A stack is used by programming languages for implementing function calls. Here's a handy C program to check how function calls are made using stack.



#include < stdio.h >
#include < conio.h >
#include < stdlib.h >
#include < dos.h >

unsigned int far *ptr ;
void ( *p )( void ) ;

void f1( ) ;
void f2( ) ;

void main( )
{
f1( ) ;
f2( ) ;

printf ( "\nback to main..." ) ;
exit ( 1 ) ;
}

void f1( )
{
ptr = ( unsigned int far * ) MK_FP ( _SS, _SP + 2 ) ;
printf ( "\n%d", *ptr ) ;

p = ( void ( * )( ) ) MK_FP ( _CS, *ptr ) ;
( *p )( ) ;
printf ( "\nI am f1( ) function " ) ;
}

void f2( )
{
printf ( "\nI am f2( ) function" ) ;
}