C program for Binary Tree Sort Algorithm

Mr Coder August 18, 2012 1

C program for Binary Tree sort Algorithm : A Binary tree sort algorithm is a sorting algorithm that builds a binary search tree from the values or keys to be sorted, and then traverses the tree (in-order) so that the values or keys come out in sorted order. Its basically used when when sorting of elements has to be done in stream from a file. Several other sorts would have to load the elements to a temporary data structure, whereas in a binary tree sort the act of loading the input into a data structure is sorting it.  Let us see basic C program for Binary tree sort Algorithm :

C Program for Binary Tree Sort Algorithm :

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

struct btreenode
{
    struct btreenode *leftchild ;
    int data ;
    struct btreenode *rightchild ;
} ;

void insert ( struct btreenode **, int ) ;
void inorder ( struct btreenode * ) ;

int main( )
{
    struct btreenode *bt ;
    int arr[20], arr1[20]; 
    int i, num, j ;
    bt = NULL ; //initialize the node

    printf("******** Binary tree sort Algorithm by Ccodechamp ***********\n" ) ;
    printf("\n");
    printf("\nEnter the number of elements in the list : ");
    scanf("%d",&num);
    printf("\nEnter the elements to be sorted: \n");
    for(i=0;i < num;i++)
    {
                      scanf("%d",&arr[i]);
                      arr1[i]=arr[i];
                      }
    printf ( "\nDisplay Array contents:\n" ) ;
    for ( i = 0 ; i < num ; i++ )
        printf ( "%d\t", arr[i] ) ;

    for ( j = 0 ; j < num ; j++ )
        insert ( &bt, arr1[j] ) ;

    printf ( "\nIn-order traversal of binary tree:\n" ) ;
    inorder ( bt ) ;

    getch( ) ;
}

void insert ( struct btreenode **sr, int num1 )
{
    if ( *sr == NULL )
    {
        *sr = malloc ( sizeof ( struct btreenode ) ) ;

        ( *sr ) -> leftchild = NULL ;
        ( *sr ) -> data = num1 ;
        ( *sr ) -> rightchild = NULL ;
    }
    else
    {
        if ( num1 < ( *sr ) -> data )
            insert ( &( ( *sr ) -> leftchild ), num1 ) ;
        else
            insert ( &( ( *sr ) -> rightchild ), num1 ) ;
    }
}

void inorder ( struct btreenode *sr )
{
    if ( sr != NULL )
    {
        inorder ( sr -> leftchild ) ;
        printf ( "%d\t", sr -> data ) ;
        inorder ( sr -> rightchild ) ;
    }
}

 

We hope you all have enjoyed the Binary Sort Algorithm in C. If you have any queries ask us in form of comments.

One Comment »

  1. Alfonzo Vought November 6, 2012 at 7:37 pm - Reply

    Great web site you’ve got here.. It’s difficult to find high-quality writing like yours nowadays. I honestly appreciate people like you! Take care!!

Leave A Response »