0% found this document useful (0 votes)
44 views47 pages

DSA Lab Report - Hari Rijal

The document discusses several programs involving recursion: passing an array to functions, calculating power of a number, displaying multiples of a number, and calculating factorials, Fibonacci series, and the Tower of Hanoi problem recursively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views47 pages

DSA Lab Report - Hari Rijal

The document discusses several programs involving recursion: passing an array to functions, calculating power of a number, displaying multiples of a number, and calculating factorials, Fibonacci series, and the Tower of Hanoi problem recursively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

1. Write a program how to pass array to the functions.

class Passarray{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={10,50,18,22,28,6};
min(a);
}
}

2. Write a program to ask a number and power to be calculated for that number.
import java.util.Scanner;
public class PowerUsingRecursion {
public static int power(int base, int exp){
if (exp !=0){
return (base * power(base, exp-1));
}else {
return 1;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the base number :");
int base = sc.nextInt();
System.out.println("Enter the exponent number::");
int exp = sc.nextInt();
System.out.println(power(base, exp));
}
}

3. Write a program to display first four multiple of a number using recursion.


class multipleTest{
static int multiple(int num)
{
int i=1;
if(num==0)
{
return 1;
}
else{
return(num*multiple(num-1));
}
}
public static void main(String[] args)
{
System.out.println(multiple(4));
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}
class multipleTest{
static int multiple(int num)
{
int i=1;
if(num==0)
{
return 1;
}
else{
return(num*multiple(num-1));
}
}
public static void main(String[] args)
{
System.out.println(multiple(4));
}

4. Write a program to find the multiplication of natural numbers using recursion.

5. Write a program to calculate factorial of a number, number being entered by user.


import java.util.Scanner;
class Factorial {
int fact(int n, int result){
if(n==1){
return result;
}
else{
return(fact(n-1,n*result));
}
}
}
class FactorialDemo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
Factorial f=new Factorial();
System.out.print("Enter a number ");
int n=sc.nextInt();
System.out.println("Factorial of "+n+" is "+f.fact(n,1));
}
}

6. Write a program to calculate the nth number of the Fibonacci series.


import java.util.Scanner;
class Fibonacci{
int fibo(int n){
int result;
if(n<=1){
return n;
}
else{
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
return(fibo(n-1)+fibo(n-2));
}
}
}
class FibonacciDemo{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
Fibonacci f=new Fibonacci();
System.out.print("Enter a number: ");
int n=sc.nextInt();
System.out.println("Fibonacci series for "+n+" elements: ");
for(int i=1;i<=n;i++){
System.out.println(f.fibo(i));
}
}
}

7. Implement the Tower of Hanoi Problem recursively.


import java.util.Scanner;
public class TowersOfHanoi {
static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {
if (n == 1) {
System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
public static void main(String args[]) {
System.out.println("Enter number of disks :- ");
Scanner scanner = new Scanner(System.in);
int n= scanner.nextInt();
System.out.println("Move disks as below illustration.");
towerOfHanoi(n, 'A', 'C', 'B');
}
}

8. Write a program to multiply two matrices and get the transpose of the third one.
public class MatrixMultiplicationExample{
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int original[][]={{1,3,4},{2,4,3},{3,4,5}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
}
System.out.println();
}
int transpose[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+" ");
}
System.out.println();
}
}
}
public static void main(String args[]){
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int original[][]={{1,3,4},{2,4,3},{3,4,5}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();
}
int transpose[][]=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+" ");
}
System.out.println();
}
}
}

9. Write a program to evaluate a post fix expression.

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


10.Write a program to convert infix to postfix expression.
import java.util.Stack;
class Test
{
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}
static String infixToPostfix(String exp)
{
String result = new String("");
Stack<Character> stack = new Stack<>();
for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();

if (!stack.isEmpty() && stack.peek() != '(')


return "Invalid Expression";
else
stack.pop();
}
else // an operator is encountered
{
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek())){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
stack.push(c);
}

}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
// pop all the operators from the stack
while (!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
return result;
}
public static void main(String[] args)
{
String exp = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(exp));
}
}
11.Write a program to evaluate a prefix expression.
import java.io.*;
import java.util.*;
class GFG {
static Boolean isOperand(char c)
{
if (c >= 48 && c <= 57)
return true;
else
return false;
}
static double evaluatePrefix(String exprsn)
{
Stack<Double> Stack = new Stack<Double>();

for (int j = exprsn.length() - 1; j >= 0; j--) {


if (isOperand(exprsn.charAt(j)))
Stack.push((double)(exprsn.charAt(j) - 48));
else {
double o1 = Stack.peek();
Stack.pop();
double o2 = Stack.peek();
Stack.pop();
switch (exprsn.charAt(j)) {
case '+':
Stack.push(o1 + o2);
break;
case '-':
Stack.push(o1 - o2);
break;
case '*':
Stack.push(o1 * o2);
break;
case '/':
Stack.push(o1 / o2);
break;
}
}
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
return Stack.peek();
}
public static void main(String[] args)
{
String exprsn = "+9*26";
System.out.println(evaluatePrefix(exprsn));
}
}
import java.io.*;
import java.util.*;

class GFG {

static Boolean isOperand(char c)


{
if (c >= 48 && c <= 57)
return true;
else
return false;
}

static double evaluatePrefix(String exprsn)


{
Stack<Double> Stack = new Stack<Double>();

for (int j = exprsn.length() - 1; j >= 0; j--) {


if (isOperand(exprsn.charAt(j)))
Stack.push((double)(exprsn.charAt(j) - 48));

else {
double o1 = Stack.peek();
Stack.pop();
double o2 = Stack.peek();
Stack.pop();
switch (exprsn.charAt(j)) {
case '+':
Stack.push(o1 + o2);
break;
case '-':
Stack.push(o1 - o2);
break;
case '*':
Stack.push(o1 * o2);
break;
case '/':
Stack.push(o1 / o2);
break;
}
}
}
return Stack.peek();
}
public static void main(String[] args)

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


{
String exprsn = "+9*26";
System.out.println(evaluatePrefix(exprsn));
}
}

12. Write a program to multiply two matrices and get the transpose of the third one

13.Write a menu driven program to implement stack operation using array.


class Stack{
private char[] data;
private int tos;
public Stack(){}
public Stack(int size){
data = new char[size];
tos = 0;
}
public void push(char ch){
if(isFull()){
System.out.println("Stack is Full");
return;
}
data[tos++] = ch;
}
public char pop(){
if(isEmpty()){
System.out.println("The stack is empty");
return(char) 0;
}
return data[--tos];
}
public boolean isFull(){
return tos ==data.length;
}
public boolean isEmpty(){
return tos==0;
}
}
public class StackDemo {
public static void main(String[] args) {
Stack s = new Stack(30);
for(int i=0;i<26;i++)
s.push((char)('A'+i));
System.out.println("Popping Data Items from the stack");
while(!s.isEmpty())
System.out.print(s.pop()+ " ");
}
}

14. Write a menu driven program to implement linear queue using array.

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


15.Write a menu driven program to implement circular queue using array
import java.util.Scanner;
public class CircularQueue{
public static void main(String args[]){
Queue1 obj = new Queue1();
int i;
Scanner sc =new Scanner(System.in);
do{
System.out.println("Menu\n1.insert\t2.delete\t3.display\t4.destroy\t5.exit");
System.out.print("Enter choice :");
i=sc.nextInt();
switch(i){
case 1:
System.out.print("Enter data to insert:");
int mk=sc.nextInt();
obj.insert(mk);
break;
case 2:
if(obj.empty())
System.out.println("Queue underflow");
else{
int km =obj.delete();
System.out.println("data deleted =" + km );
}
break;
case 3: obj.display();
break;
case 4: obj.destroy();
break;
case 5: break;
default : System.out.println("Wrong Choice");
}
}while(i!=5);
}
}
class Queue1{
int mk[];
int front, rear;
Queue1(){
mk = new int [100];
front = rear = 1;
}
Queue1(int size){
mk = new int[size];
front = rear = -1;
}
void insert(int x){
int mi;
mi = (rear+1)% mk.length;
if(mi == front)
System.out.println("Queue Overflow ");
else
{
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
rear = mi;
mk[rear] = x;
if(front == -1)
front = 0;
}
}
boolean empty()
{
if(front == -1)
return true;
else
return false;
}
int delete(){
int kar = mk[front];
if(front == rear)
front = rear = -1;
else
front =(front+1)% mk.length;
return kar;
}
void display(){
if(front == -1)
System.out.println("Queue underflow");
else{
System.out.println("Elements of Queue are");
int i = front;
while(i != rear)
{
System.out.println(mk[i]);
i = (i+1)% mk.length;
}
System.out.println(mk[i]);
}
}
void destroy(){
front = rear=-1;
}
}

16.Write a menu driven program to implement priority queue.


class PQNode
{
public int info;
public int prt;
public PQNode next;
public PQNode(){
info = 0;
prt = 0;
next = null;
}
public PQNode(int el,int p){
info = el;
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
prt = p;
}
}
class PriorityQueue
{
private PQNode front;
private PQNode rear;
public PriorityQueue(){
front = null;
rear = null;
}
public boolean isEmpty(){
return front == null;
}
public void dequeue(){
if(front==null)
front = rear = null;
else
{
front = front.next;
if(front == null)
rear=null;
}
}
public void display(){
PQNode temp;
for(temp=front;temp!=rear;temp = temp.next)
System.out.print(temp.info+ "-");
System.out.print(temp.info);
}
public void enqueue(int el,int p){
PQNode temp = new PQNode(el,p);
PQNode temp1,temp2;
temp1 =temp2 = front;
if(rear==null){
rear = temp;
front = rear;
}
else if(p<=rear.prt)
{
rear.next = temp;
rear = temp;
}
else if(p>front.prt)
{
temp.next = front;
front = temp;
}
else
{
while(temp2.prt>=p){
temp1 = temp2;
temp2 = temp2.next;

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


if(temp2==null)return;
}
temp1.next = temp;
temp.next = temp2;
if(temp2 == null){
rear.next = temp;
rear = temp;
}
}
}
}
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
q.enqueue(50, 0);
q.enqueue(40, 1);
q.enqueue(30, 0);
q.enqueue(20, 0);
q.enqueue(10, 0);
q.enqueue(0, 2);
System.out.println("Priority Queue before deletion");
q.display();
q.dequeue();
System.out.println("\nPriority Queue after deletion");
q.display();
}
}

17.Write a menu driven program to illustrate basic operations of singly linked list with
following operations:
//insertion
import java.util.Scanner;
class LinkedList{
Node head;
class Node {
int data;
Node next;
Node(int d) {data = d; next = null; }
}
public void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public void insertAfter(Node prev_node, int new_data) {
if (prev_node == null) {
System.out.println("The given previous node cannot be null");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_node.next;
prev_node.next = new_node;
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
public void append(int new_data) {
Node new_node = new Node(new_data);
if (head == null){
head = new Node(new_data);
return;
}
new_node.next = null;
Node last = head;
while (last.next != null)
last = last.next;
last.next = new_node;
return;
}
public void printList() {
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
LinkedList llist = new LinkedList();
System.out.print("Enter the size of data you want to add at beginning:");
int n1=sc.nextInt();
for(int i=0;i<n1;i++){
llist.push(sc.nextInt());
}
llist.printList();
System.out.print("\nEnter the size of data you want to add at end:");
int n2=sc.nextInt();
for(int i=0;i<n2;i++){
llist.append(sc.nextInt());
}
llist.printList();
llist.insertAfter(llist.head.next, 8);
System.out.println("\nCreated Linked list is: ");
llist.printList();
}
}
//deletion
import java.util.Scanner;
public class SinglyLinkedListDeletion {
class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public Node head = null;

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


public Node tail = null;
public void addNode(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
}
public void deleteFromStart() {
if(head == null) {
System.out.println("List is empty");
return;
}
else {
if(head != tail) {
head = head.next;
}
else {
head = tail = null;
}
}
}
public void deleteFromEnd() {
if(head == null) {
System.out.println("List is empty");
return;
}
else {
if(head != tail ) {
Node current = head;
while(current.next != tail) {
current = current.next;
}
tail = current;
tail.next = null;
}
else {
head = tail = null;
}
}
}
public void deleteNodeAtPostion(int position) {
if (head == null)
return;
Node temp = head;
if (position == 0) {
head = temp.next;
return;
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


for (int i=0; temp!=null && i<position-1; i++)
temp = temp.next;
if (temp == null || temp.next == null)
return;
Node next = temp.next.next;
temp.next = next;
}
public void display() {
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
SinglyLinkedListDeletion sList = new SinglyLinkedListDeletion();
System.out.print("Enter the size of Link list:");
int n1=sc.nextInt();
for(int i=0;i<n1;i++){
sList.addNode(sc.nextInt());
}
System.out.println("Original List: ");
sList.display();
sList.deleteFromStart();
System.out.println("Updated List after deletion from start: ");
sList.display();
sList.deleteFromEnd();
System.out.println("Updated List after deletion from end: ");
sList.display();
System.out.print("Enter the postion from where you want to delete:");
int n=sc.nextInt();
sList.deleteNodeAtPostion(n);
System.out.println("Updated List after deletion at postion "+n+": ");
sList.display();
}
}

18. Write a menu driven program to implement a stack as a linked list


import java.util.Scanner;
class Node{
protected int data;
protected Node next;
public Node(){
next = null;
data = 0;
}
public Node(int d){
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
data = d;
next = null;
}
}
class linkedStack{
protected Node top ;
protected int size ;
public linkedStack(){
top = null;
size = 0;
}
public boolean isEmpty(){
return top == null;
}
public void push(int data){
Node ptr = new Node (data);
if (top == null)
top = ptr;
else{
ptr.next = top;
top = ptr;
}
size++ ;
}
public int pop(){
if (isEmpty() )
return 0;
Node ptr = top;
top = ptr.next;
size-- ;
return ptr.data;
}
public void display(){
if (size == 0){
System.out.print("Empty\n");
return ;
}
Node ptr = top;
while (ptr != null)
{
System.out.print(ptr.data+" ");
ptr = ptr.next;
}
System.out.println();
}
}
public class LinkedStackImplement{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
linkedStack ls = new linkedStack();
System.out.print("Enter the size of link list:");
int n=sc.nextInt();
for(int i=0;i<n;i++){

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


ls.push(sc.nextInt());
System.out.println("Stack Push Opertaion");
ls.display();
}
System.out.println("Stack Pop opertaion:");
for(int i=0;i<n;i++){
ls.pop();
ls.display();
}
}
}

19. Write a menu program driven to implement a queue as a linked list


import java.util.Scanner;
class QNode{
public int info;
public QNode next;
public QNode(){
info = 0;
next = null;
}
public QNode(int el){
info = el;
next = null;
}
}
class Queue{
private QNode front;
private QNode rear;
public Queue(){
front = null;
rear = null;
}
public boolean isEmpty(){
return front==null;
}
public void enqueue(int el){
QNode temp = new QNode(el);
if(rear==null){
rear = temp;
front = rear;
}
else{
rear.next = temp;
rear = temp;
}
}
public void dequeue(){
QNode temp;
if(front==null){
System.out.println("Queue is empty");
front = rear = null;
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
else{
front = front.next;
}
}
public void display()
{
QNode temp = front;
while (temp != null)
{
System.out.print(temp.info+" ");
temp = temp.next;
}
System.out.println();
}
}
public class LinkedListQueue {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Queue q = new Queue();
System.out.print("Enter the size of link list:");
int n=sc.nextInt();
for(int i=0;i<n;i++){
q.enqueue(sc.nextInt());
System.out.println("Dequeue Operation:");
q.display();
}
for(int i=0;i<n;i++){
System.out.println("Dequeue Operation:");
q.dequeue();
q.display();
}
}
}

20.Write a menu program to demonstrate operations of doubly linked list.


//insertion
import java.util.Scanner;
public class DLL {
Node head;
class Node {
int data;
Node prev;
Node next;
Node(int d) { data = d; }
}
public void push(int new_data) {
Node new_Node = new Node(new_data);
new_Node.next = head;
new_Node.prev = null;
if (head != null)
head.prev = new_Node;
head = new_Node;
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
public void InsertAfter(Node prev_Node, int new_data) {
if (prev_Node == null) {
System.out.println("The given previous node cannot be NULL ");
return;
}
Node new_node = new Node(new_data);
new_node.next = prev_Node.next;
prev_Node.next = new_node;
new_node.prev = prev_Node;
if (new_node.next != null)
new_node.next.prev = new_node;
}
void append(int new_data) {
Node new_node = new Node(new_data);
Node last = head;
new_node.next = null;
if (head == null) {
new_node.prev = null;
head = new_node;
return;
}
while (last.next != null)
last = last.next;
last.next = new_node;
new_node.prev = last;
}
public void printlist(Node node) {
Node last = null;
System.out.println("Traversal in forward Direction");
while (node != null) {
System.out.println(node.data );
last = node;
node = node.next;
}
System.out.println();
System.out.println("Traversal in reverse direction");
while (last != null) {
System.out.println(last.data + " ");
last = last.prev;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
DLL dll = new DLL();
System.out.print("Enter the size of data you want to add at beginning:");
int n1=sc.nextInt();
for(int i=0;i<n1;i++){
dll.push(sc.nextInt());
}
System.out.print("\nEnter the size of data you want to add at end:");
int n2=sc.nextInt();
for(int i=0;i<n2;i++){
dll.append(sc.nextInt());

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}
dll.InsertAfter(dll.head.next, 23);
System.out.println("Created DLL is: ");
dll.printlist(dll.head);
}
}
//deletion
import java.util.Scanner;
public class DLLDeletion {
class Node{
int data;
Node previous;
Node next;
public Node(int data) {
this.data = data;
}
}
public int size = 0;
Node head, tail = null;
public void addNode(int data) {
Node newNode = new Node(data);
if(head == null) {
head = tail = newNode;
head.previous = null;
tail.next = null;
}
else {
tail.next = newNode;
newNode.previous = tail;
tail = newNode;
tail.next = null;
}
size++;
}
public void deleteFromStart() {
if(head == null) {
return;
}
else {
if(head != tail) {
head = head.next;
head.previous = null;
}
else {
head = tail = null;
}
}
}
public void deleteFromEnd() {
if(head == null) {
return;
}
else {

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


if(head != tail) {
tail = tail.previous;
tail.next = null;
}
else {
head = tail = null;
}
}
}
public void deleteNodeAtPostion(int position){
if(head == null) {
return;
}
else {
Node current = head;
for(int i = 0; i < position; i++){
current = current.next;
}
if(current == head) {
head = current.next;
}
else if(current == tail) {
tail = tail.previous;
}
else {
current.previous.next = current.next;
current.next.previous= current.previous;
}
current = null;
}
size--;
}
public void display() {
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
while(current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
DLLDeletion dList = new DLLDeletion();
System.out.print("Enter the size of Link list:");
int n1=sc.nextInt();
for(int i=0;i<n1;i++){
dList.addNode(sc.nextInt());
}
System.out.println("Original List: ");

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


dList.display();
dList.deleteFromStart();
System.out.println("Updated List after deletion from start: ");
dList.display();
dList.deleteFromEnd();
System.out.println("Updated List after deletion from end: ");
dList.display();
System.out.print("Enter the postion from where you want to delete:");
int n=sc.nextInt();
dList.deleteNodeAtPostion(n);
System.out.println("Updated List after deletion at postion "+n+": ");
dList.display();
}
}

21.Write a menu program to demonstrate operations of circular linked list.


import java.util.Scanner;
class CLLNode
{
int info;
CLLNode next;
CLLNode first,last;
CLLNode(){
info=0;
next=first;
}
void insert_CLLstart(int data)
{
CLLNode Newnode=new CLLNode();
Newnode.info=data;
if(first==null){
Newnode.next=Newnode;
first=Newnode;
last=Newnode;
}
else{
Newnode.next=first;
first=Newnode;
last.next=Newnode;
}
}
void insert_CLLend(int data){
CLLNode Newnode=new CLLNode();
Newnode.info=data;
if(first==null){
Newnode.next=Newnode;
first=Newnode;
last=Newnode;
}
else{
last.next=Newnode;
last=Newnode;
Newnode.next=first;
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
}
}
void delete_first(){
if(first==null){
System.out.println("Linked List is empty");
}
else if(first==last){
first=null;
last=null;
System.out.println("Deleted item=" +first.info);
}
else{
first=first.next;
last.next=first;
}
}
void delete_last(){
if(first==null){
System.out.println("Linked List is empty");
}
else if(first==last){
first=null;
last=null;
}
else{
CLLNode temp=new CLLNode();
temp=first;
while(temp.next!=last){
temp=temp.next;
}
last=temp;
last.next=first;
}
}
void display(){
CLLNode temp=new CLLNode();
temp=first;
while(temp!=last){
System.out.println("Node=" +temp.info);
temp=temp.next;
}
}
}
class CLLDemo{
public static void main(String[] args)
{
CLLNode obj=new CLLNode();
int i;
Scanner sc =new Scanner(System.in);
do{
System.out.println("Menu\n1.insert at beginning\n2.insert at end\n3.delete at
beginning\n4.delete at end\n5.display\n6.exit");
System.out.print("Enter choice :");

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


i=sc.nextInt();
switch(i){
case 1:
System.out.print("Enter data to insert:");
int mk=sc.nextInt();
obj.insert_CLLstart(mk);
break;
case 2:
System.out.print("Enter data to insert:");
int mk=sc.nextInt();
obj.insert_CLLend(mk);
break;
case 3:
obj.delete_first();
break;
case 4:
obj.delete_last();
break;
case 5:
obj.display();
break;
case 6:
break;
default :
System.out.println("Wrong Choice");
}
}while(i!=6)
}
}

22.Write a menu driven program to implement Binary search tree operation (insertion,
deletion and searching).
class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
void insert(int key) {
root = insertRec(root, key);
}
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

tree.inorder();
}
}
class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
void insert(int key) {
root = insertRec(root, key);
}
Node insertRec(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


root.right = insertRec(root.right, key);
return root;
}
void inorder() {
inorderRec(root);
}
void inorderRec(Node root) {
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
tree.inorder();
}
}

23.*Write a menu driven program to implement AVL tree.


class Node {
int key, height;
Node left, right;
Node(int d) {
key = d;
height = 1;
}
}
class AVLTree {
Node root;
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;
return x;
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
}
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = max(height(x.left), height(x.right)) + 1;
y.height = max(height(y.left), height(y.right)) + 1;
return y;
}
int getBalance(Node N) {
if (N == null)
return 0;
return height(N.left) - height(N.right);
}
Node insert(Node node, int key) {
if (node == null)
return (new Node(key));
if (key < node.key)
node.left = insert(node.left, key);
else if (key > node.key)
node.right = insert(node.right, key);
else
return node;
node.height = 1 + max(height(node.left),
height(node.right));
int balance = getBalance(node);
if (balance > 1 && key < node.left.key)
return rightRotate(node);

// Right Right Case


if (balance < -1 && key > node.right.key)
return leftRotate(node);

// Left Right Case


if (balance > 1 && key > node.left.key) {
node.left = leftRotate(node.left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node.right.key) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
}
void preOrder(Node node) {
if (node != null) {
System.out.print(node.key + " ");
preOrder(node.left);
preOrder(node.right);
}
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


public static void main(String[] args) {
AVLTree tree = new AVLTree();
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 20);
tree.root = tree.insert(tree.root, 30);
tree.root = tree.insert(tree.root, 40);
tree.root = tree.insert(tree.root, 50);
tree.root = tree.insert(tree.root, 25);
System.out.println("Preorder traversal" +
" of constructed tree is : ");
tree.preOrder(tree.root);
}
}

24. Write a menu driven program to implement B-tree.

25.Write program to implement Bubble sort algorithm.


import java.util.Scanner;
class BubbleSort{
void bubbleSort(int arr[]){
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size_arr= scan.nextInt();
int arr[] = new int[size_arr];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}
BubbleSort ob_arr = new BubbleSort();
System.out.print("Array are :\n");
for (int i = 0; i < size_arr; ++i){
System.out.print(arr[i] + " ");
}
System.out.println();
ob_arr.bubbleSort(arr);
System.out.println("Sorted array");
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
ob_arr.printArray(arr);
}
}
import java.util.Scanner;
class BubbleSort{
void bubbleSort(int arr[]){
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size_arr= scan.nextInt();
int arr[] = new int[size_arr];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}
BubbleSort ob_arr = new BubbleSort();
System.out.print("Array are :\n");
for (int i = 0; i < size_arr; ++i){
System.out.print(arr[i] + " ");
}
System.out.println();
ob_arr.bubbleSort(arr);
System.out.println("Sorted array");
ob_arr.printArray(arr);
}
}

26.Write program to implement Insertion sort algorithm.


import java.util.Scanner;
class InsertionSort {
void sort(int arr[]) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[]) {
int n = arr.length;
System.out.print("Now the Array after Sorting is :\n");
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size_arr= scan.nextInt();
int arr[] = new int[size_arr];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}
System.out.print("Array are :\n");
for (int i = 0; i < arr.length; ++i){
System.out.print(arr[i] + " ");
}
System.out.println();
InsertionSort ob_arr = new InsertionSort();
ob_arr.sort(arr);
printArray(arr);
System.out.println("MiLan,B,10");
}
}
import java.util.Scanner;
class InsertionSort {
void sort(int arr[]) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
static void printArray(int arr[]) {
int n = arr.length;
System.out.print("Now the Array after Sorting is :\n");
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size_arr= scan.nextInt();
int arr[] = new int[size_arr];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}
System.out.print("Array are :\n");
for (int i = 0; i < arr.length; ++i){
System.out.print(arr[i] + " ");
}
System.out.println();
InsertionSort ob_arr = new InsertionSort();
ob_arr.sort(arr);
printArray(arr);
System.out.println("MiLan,B,10");
}
}

27.Write program to implement Selection sort algorithm.


import java.util.Scanner;
public class SelectionSortExample {
public static void main(String args[]) {
int size_arr, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size_arr = scan.nextInt();
System.out.print("Enter Array Elements : ");
for(i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}

System.out.print("Array are :\n");


for (i = 0; i < size_arr;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
for(i=0; i<size_arr; i++) {
for(j=i+1; j<size_arr; j++){
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n");
for(i=0; i<size_arr; i++){
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
System.out.print(arr[i]+ " ");
}
System.out.println();
}
}
import java.util.Scanner;
public class SelectionSortExample {
public static void main(String args[]) {
int size_arr, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
size_arr = scan.nextInt();
System.out.print("Enter Array Elements : ");
for(i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}

System.out.print("Array are :\n");


for (i = 0; i < size_arr;i++){
System.out.print(arr[i] + " ");
}
System.out.println();
for(i=0; i<size_arr; i++) {
for(j=i+1; j<size_arr; j++){
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.print("Now the Array after Sorting is :\n");
for(i=0; i<size_arr; i++){
System.out.print(arr[i]+ " ");
}
System.out.println();
}
}

28.Write program to implement Quick sort algorithm.


import java.util.Scanner;
class QuickSort{
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low-1);
for (int j=low; j<high; j++) {
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
void sort(int arr[], int low, int high) {
if (low < high){
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size= scan.nextInt();
int arr[] = new int[size];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size; i++){
arr[i] = scan.nextInt();
}
System.out.print("Array are :\n");
for (int i = 0; i < size; ++i){
System.out.print(arr[i] + " ");
}
System.out.println();
QuickSort ob = new QuickSort();
ob.sort(arr, 0, size-1);
System.out.println("Sorted Array");
printArray(arr);
}
}
import java.util.Scanner;
class QuickSort{
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low-1);
for (int j=low; j<high; j++) {
if (arr[j] <= pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
void sort(int arr[], int low, int high) {
if (low < high){
int pi = partition(arr, low, high);
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size= scan.nextInt();
int arr[] = new int[size];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size; i++){
arr[i] = scan.nextInt();
}
System.out.print("Array are :\n");
for (int i = 0; i < size; ++i){
System.out.print(arr[i] + " ");
}
System.out.println();
QuickSort ob = new QuickSort();
ob.sort(arr, 0, size-1);
System.out.println("Sorted Array");
printArray(arr);
}
}

29.Write program to implement Merge sort algorithm.


import java.util.Scanner;
class MergeSort{
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
int i = 0, j = 0;
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r) {
if (l < r) {
int m = (l+r)/2;
sort(arr, l, m);
sort(arr , m+1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Array Size : ");
int size_arr= scan.nextInt();
int arr[] = new int[size_arr];
System.out.print("Enter Array Elements : ");
for(int i=0; i<size_arr; i++){
arr[i] = scan.nextInt();
}
System.out.println("Given Array");
printArray(arr);
MergeSort ob_arr = new MergeSort();
ob_arr.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


30.Write program to implement Heap sort algorithm.
public class HeapSort
{
public void sort_arr(int arr[])
{
int n = arr.length;
for (int i_arr = n / 2 - 1; i_arr >= 0; i_arr--)
heapify_arr(arr, n, i_arr);
for (int i_arr=n-1; i_arr>=0; i_arr--)
{
int temp = arr[0];
arr[0] = arr[i_arr];
arr[i_arr] = temp;
heapify_arr(arr, i_arr, 0);
}
}
void heapify_arr(int arr[], int n, int i)
{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify_arr(arr, n, largest);
}
}
static void printArray_arr(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
public static void main(String args[])
{
int arr[] = {12, 11, 13, 56,8,32,1,10};
int n = arr.length;
HeapSort ob = new HeapSort();
ob.sort_arr(arr);
System.out.println("Sorted array is");
printArray_arr(arr);
}
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


31. Write program to implement Radix sort algorithm.
public class RadixSort {
public static void main(String[] args) {
int i;
int[] a = {90,23,101,45,65,23,67,89,34,23};
radix_sort(a);
System.out.println("\n The sorted array is: \n");
for(i=0;i<10;i++)
System.out.println(a[i]);
}
static int largest(int a[])
{
int larger=a[0], i;
for(i=1;i<10;i++)
{
if(a[i]>larger)
larger = a[i];
}
return larger;
}
static void radix_sort(int a[])
{
int bucket[][]=new int[10][10];
int bucket_count[]=new int[10];
int i, j, k, remainder, NOP=0, divisor=1, larger, pass;
larger = largest(a);
while(larger>0)
{
NOP++;
larger/=10;
}
for(pass=0;pass<NOP;pass++)
{
for(i=0;i<10;i++)
bucket_count[i]=0;
for(i=0;i<10;i++)
{
remainder = (a[i]/divisor)%10;
bucket[remainder][bucket_count[remainder]] = a[i];
bucket_count[remainder] += 1;
}
i=0;
for(k=0;k<10;k++)
{
for(j=0;j<bucket_count[k];j++)
{
a[i] = bucket[k][j];
i++;
}
}
divisor *= 10;
}
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
}
public class RadixSort {
public static void main(String[] args) {
int i;
int[] a = {90,23,101,45,65,23,67,89,34,23};
radix_sort(a);
System.out.println("\n The sorted array is: \n");
for(i=0;i<10;i++)
System.out.println(a[i]);
}
static int largest(int a[])
{
int larger=a[0], i;
for(i=1;i<10;i++)
{
if(a[i]>larger)
larger = a[i];
}
return larger;
}
static void radix_sort(int a[])
{
int bucket[][]=new int[10][10];
int bucket_count[]=new int[10];
int i, j, k, remainder, NOP=0, divisor=1, larger, pass;
larger = largest(a);
while(larger>0)
{
NOP++;
larger/=10;
}
for(pass=0;pass<NOP;pass++)
{
for(i=0;i<10;i++)
bucket_count[i]=0;
for(i=0;i<10;i++)
{
remainder = (a[i]/divisor)%10;
bucket[remainder][bucket_count[remainder]] = a[i];
bucket_count[remainder] += 1;
}
i=0;
for(k=0;k<10;k++)
{
for(j=0;j<bucket_count[k];j++)
{
a[i] = bucket[k][j];
i++;
}
}
divisor *= 10;
}
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}

32.Write program to implement linear (sequential) search algorithm.


import java.util.Scanner;
public class LinearSearchDemo {
public static void main(String args[]) {
int i, n, search, array[];
Scanner sc= new Scanner(System.in);
System.out.print("Enter size of elements: ");
n = sc.nextInt();
array = new int[n];
System.out.println("Enter " + n + " elements");
for (i = 0; i < n; i++){
array[i] = sc.nextInt();
}
System.out.print("Enter value to find: ");
search = sc.nextInt();
for (i = 0; i < n; i++) {
if (array[i] == search) {
System.out.println(search + " is present at location " + (i + 1) + ".");
break;
}
}
if (i == n){
System.out.println(search + " isn't present in array.");
}
}
}
import java.util.Scanner;
public class LinearSearchDemo {
public static void main(String args[]) {
int i, n, search, array[];
Scanner sc= new Scanner(System.in);
System.out.print("Enter size of elements: ");
n = sc.nextInt();
array = new int[n];
System.out.println("Enter " + n + " elements");
for (i = 0; i < n; i++){
array[i] = sc.nextInt();
}
System.out.print("Enter value to find: ");
search = sc.nextInt();
for (i = 0; i < n; i++) {
if (array[i] == search) {
System.out.println(search + " is present at location " + (i + 1) + ".");
break;
}
}
if (i == n){
System.out.println(search + " isn't present in array.");
}
}
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
33.Write program to implement Binary search algorithm.
import java.util.Scanner;
class BinarySearch{
public static void binarySearch(int arr[], int first, int last, int key){
int mid_arr= (first + last)/2;
while( first <= last ){
if ( arr[mid_arr] < key ){
first = mid_arr + 1;
}else if ( arr[mid_arr] == key ){
System.out.println("Element is found at location: " + (mid_arr+1));
break;
}else{
last = mid_arr - 1;
}
mid_arr = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
Scanner sc_arr=new Scanner(System.in);
System.out.println("Enter size of data:");
int n=sc_arr.nextInt();
int arr[]=new int[n];
System.out.println("Enter elements in array:");
for(int i=0;i<n;i++){
arr[i]=sc_arr.nextInt();
}
System.out.println("Enter the element to be searched:");
int key=sc_arr.nextInt();
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}

34.Write a program to implement linear probing.


import java.util.Scanner;
class LinearHash{
public int arr[];
public LinearHash(){
arr = new int[0];
}
public LinearHash(int len){
int p = nextPrime(len);
arr = new int[p];
}
public void initialize(){
for(int i=0;i<arr.length;i++){
arr[i]=-1;
}
}
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
public void insertMidSQ(int num){
int mid = midSquare(num);
int N = arr.length;
int i = mid%N;
int j = i+1;
if(arr[i]==-1)
arr[i] = num;
else{
while(j!=i){
j = (j+1)%N;
if(arr[j]==-1){
arr[j] = num;
break;
}
}
}
}
public void insertExtract(int num){
int s = extract(num);
int N = arr.length;
int i = s%N;
int j = i+1;
if(arr[i]==-1)
arr[i] = num;
else{
11
while(j!=i){
j = (j+1)%N;
if(arr[j]==-1){
arr[j] = num;
break;
}
}
}
}
public int extract(int n){
int s = 0;
while(n>0)
{
s = s+n%10;
n = n/10;
}
return s;
}
public int midSquare(int n){
int s = n*n;
int mid = s/100;
mid = mid/10;
return mid;
}
public void insertDiv(int num){
int N = arr.length;
int i = num%N;

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


int j = i;
if(arr[i]==-1)
arr[i] = num;
else{
do{
j = (j+1)%N;
if(arr[j]==-1){
arr[j] = num;
break;
}
}while(j!=i);
}
}
public void delete(int num){
12
int N = arr.length;
int i= num%N;
int j = i;
int t = i;
if(arr[i]==num)
arr[i]=-1;
do{
j = (j+1)%N;
if(arr[j]%N==t){
arr[t] = arr[j];
arr[j]=-1;
t = (t+1)%N;
}
}while(j!=i);
}
public boolean Search(int num){
boolean b = false;
int N = arr.length;
int i = num%N;
int j = i;
if(arr[i]==num)
b = true;
else{
do{
j = (j+1)%N;
if(arr[j]==num){
b = true;
break;
}
}while(j!=i);
}
return b;
}
public void display(){
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}
public int nextPrime(int n){
int t=0,p=0;
for(int i=n;t!=1;i++)
{
t = isPrime(i);
if(t==1)
{
p = i;
break;
}
}
return p;
}
public int isPrime(int n){
int i,j,t=0,b=0;
for(j=1;j<=n;j++)
{
if(n%j==0)
t++;
if(t>2)
break;
}
if(t==2)
b =1;
return b;
}
}
public class HashingDemo {
public static void main(String[] args) {
int data[]={13,14,1,2,9,28};
LinearHash h = new LinearHash(data.length);
h.initialize();
int n;
for(int i=0;i<data.length;i++)
{
h.insertDiv(data[i]);
}
System.out.println("The array is ");
h.display();
Scanner s = new Scanner(System.in);
System.out.println("\nEnter number to be searched");
n = s.nextInt();
if(h.Search(n))
System.out.println("Number found");
else
System.out.println("Number not found");
System.out.println("\nEnter number to delete");
n = s.nextInt();
h.delete(n);
System.out.println("The hash table after deletion");
h.display();
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}

35.Write a program to implement quadratic probing.


import java.util.Scanner;
class QuadraticProbingHashTable
{
private int currentSize, maxSize;
private String[] keys;
private String[] vals;
public QuadraticProbingHashTable(int capacity)
{
currentSize = 0;
maxSize = capacity;
keys = new String[maxSize];
vals = new String[maxSize];
}
public void makeEmpty()
{
currentSize = 0;
keys = new String[maxSize];
vals = new String[maxSize];
}
public int getSize()
{
return currentSize;
}
public boolean isFull()
{
return currentSize == maxSize;
}
public boolean isEmpty()
{
return getSize() == 0;
}
public boolean contains(String key)
{
return get(key) != null;
}
private int hash(String key)
{
return key.hashCode() % maxSize;
}
public void insert(String key, String val)
{
int tmp = hash(key);
int i = tmp, h = 1;
do
{
if (keys[i] == null)
{
keys[i] = key;
vals[i] = val;
currentSize++;
Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com
return;
}
if (keys[i].equals(key))
{
vals[i] = val;
return;
}
i = (i + h * h++) % maxSize;
} while (i != tmp);
}
/** Function to get value for a given key **/
public String get(String key)
{
int i = hash(key), h = 1;
while (keys[i] != null)
{
if (keys[i].equals(key))
return vals[i];
i = (i + h * h++) % maxSize;
System.out.println("i "+ i);
}
return null;
}
/** Function to remove key and its value **/
public void remove(String key)
{
if (!contains(key))
return;
/** find position key and delete **/
int i = hash(key), h = 1;
while (!key.equals(keys[i]))
i = (i + h * h++) % maxSize;
keys[i] = vals[i] = null;

/** rehash all keys **/


for (i = (i + h * h++) % maxSize; keys[i] != null; i = (i + h * h++) % maxSize)
{
String tmp1 = keys[i], tmp2 = vals[i];
keys[i] = vals[i] = null;
currentSize--;
insert(tmp1, tmp2);
}
currentSize--;
}
/** Function to print HashTable **/
public void printHashTable()
{
System.out.println("\nHash Table: ");
for (int i = 0; i < maxSize; i++)
if (keys[i] != null)
System.out.println(keys[i] +" "+ vals[i]);
System.out.println();
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}
/** Class QuadraticProbingHashTableTest **/
public class QuadraticProbing
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Hash Table Test\n\n");
System.out.println("Enter size");
QuadraticProbingHashTable qpht = new QuadraticProbingHashTable(scan.nextInt() );
char ch;
/** Perform QuadraticProbingHashTable operations **/
do
{
System.out.println("\nHash Table Operations\n");
System.out.println("1. insert ");
System.out.println("2. remove");
System.out.println("3. get");
System.out.println("4. clear");
System.out.println("5. size");

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println("Enter key and value");
qpht.insert(scan.next(), scan.next() );
break;
case 2 :
System.out.println("Enter key");
qpht.remove( scan.next() );
break;
case 3 :
System.out.println("Enter key");
System.out.println("Value = "+ qpht.get( scan.next() ));
break;
case 4 :
qpht.makeEmpty();
System.out.println("Hash Table Cleared\n");
break;
case 5 :
System.out.println("Size = "+ qpht.getSize() );
break;
default :
System.out.println("Wrong Entry \n ");
break;
}
/** Display hash table **/
qpht.printHashTable();

System.out.println("\nDo you want to continue (Type y or n) \n");


ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com


}
}

36.Write a program to delete element from a hash table.


import java.util.*;
public class Hash_Table_Demo {
public static void main(String[] args)
{
Hashtable<Integer, String> hash_table =
new Hashtable<Integer, String>();
hash_table.put(10, "Geeks");
hash_table.put(15, "4");
hash_table.put(20, "Geeks");
hash_table.put(25, "Welcomes");
hash_table.put(30, "You");
System.out.println("Initial Table is: " + hash_table);
String returned_value = (String)hash_table.remove(20);
System.out.println("Returned value is: " + returned_value);
System.out.println("New table is: " + hash_table);
}
}

Prepared By: Hari Rijal Study Notes Nepal www.studynotesnepal.com

You might also like