Practical Assignment

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

SET – C

2. Write a program to search a particular element from


an Array using Binary Search.

#include <stdio.h>

int main()

int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)

scanf("%d", &array[c]);

printf("Enter value to find\n");

scanf("%d", &search);

first = 0;

last = n - 1;

middle = (first+last)/2;

while (first <= last) {

if (array[middle] < search)

first = middle + 1;

else if (array[middle] == search) {


printf("%d found at location %d.\n", search, middle+1);

break;

else

last = middle - 1;

middle = (first + last)/2;

if (first > last)

printf("Not found! %d isn't present in the list.\n", search);

return 0;

OUTPUT –
4. Write a program to create a Binary Search Tree and
display its contents using recursive preorder,
postorder and inorder traversal.

#include <stdio.h>

#include <stdlib.h>

struct node

int data;

struct node* left;

struct node* right;

};

struct node* newNode(int data)

struct node* node = (struct node*)

malloc(sizeof(struct node));

node->data = data;

node->left = NULL;

node->right = NULL;

return(node);

void printPostorder(struct node* node)

if (node == NULL)
return;

printPostorder(node->left);

printPostorder(node->right);

printf("%d ", node->data);

void printInorder(struct node* node)

if (node == NULL)

return;

printInorder(node->left);

printf("%d ", node->data);

printInorder(node->right);

void printPreorder(struct node* node)

if (node == NULL)

return;

printf("%d ", node->data);

printPreorder(node->left);

printPreorder(node->right);

int main()

printf("\n\nBHAWANA SUMAN\n\n");
struct node *root = newNode(1);

root->left = newNode(2);

root->right = newNode(3);

root->left->left = newNode(4);

root->left->right = newNode(5);

printf("\nPreorder traversal of binary tree is \n\t");

printPreorder(root);

printf("\nInorder traversal of binary tree is \n\t");

printInorder(root);

printf("\nPostorder traversal of binary tree is \n\t");

printPostorder(root);

getchar();

return 0;

OUTPUT –
3. Write a program to make an Insertion sort of 10
numbers of elements.

#include<stdio.h>

int main(){

int i, j, count, temp, number[25];

printf("\nEnter the number of elements: ");

scanf("%d",&count);

printf("Enter %d elements: ", count);

for(i=0;i<count;i++)

scanf("%d",&number[i]);

for(i=1;i<count;i++){

temp=number[i];

j=i-1;

while((temp<number[j])&&(j>=0)){

number[j+1]=number[j];

j=j-1;

number[j+1]=temp;

printf("Order of Sorted elements: ");

for(i=0;i<count;i++)

printf(" %d",number[i]);

return 0; }
OUTPUT –

You might also like