0% found this document useful (0 votes)
10 views117 pages

DS Lab Record (Iii-I-So)

Data Structures

Uploaded by

sweetyryali6
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)
10 views117 pages

DS Lab Record (Iii-I-So)

Data Structures

Uploaded by

sweetyryali6
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/ 117

1

UNIVERSITY COLLEGE OF ENGINEERING NARASARAOPET

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITYKAKINADA

JNTUK, NARASARAOPET-522601,GUNTUR DIST.,A.P.,INDIA

DATA STRUCTURES LABORATORY RECORD

STUDENT NAME:……………………………………………………

ROLLNO :………………………………………………………………

BRANCH:………………………………………………………..……

YEAR …………………………… SEMESTER………………………..


2

CONTENTS

Week/D Name of the Program Page Mark


ate No: s
1. Write Java programs that use both
1-8-23 recursive and non-recursive functions 3-7
for implementing the following
searching methods: a) Linear search
b) Binary search
2. Write Java programs to implement
8-8-23 the list ADT using arrays and linked 8-18
lists..
3. Write Java programs to implement
15-8-23 the following using arrays and linked 19-25
lists.
4. Write a Java program that reads an 26-30
22-8-23 infix expression and converts the
expression to postfix form.(Use stack
ADT).
5. Write Java programs to implement 31-47
29-8-23 the following using a singly linked
list. a) Stack ADT b) Queue ADT
5-9-23 7. Write a Java program to implement 48-54
priority queue ADT
8. Write Java programs that use
recursive and non-recursive functions 55-82
12-9-23 to traverse the given binary tree in (a)
Preorder (b) In order and (c) Post
order.
3-10-23 9. Write a Java program that displays 83-85
node values in a level order traversal.
10. Write a Java program that uses
10-10- recursive functions. (a) To create a 86-97
23 binary search tree
11. Write Java programs for the
17-10- implementation of bfs and dfs for a 98-100
23 given graph.
12. Write Java programs for
31-10- implementing the following sorting 101-107
23 methods: (a) Bubble sort (b) Selection
sort (c) Insertion sort (d) Radix sort
13. Write a Java program for
7-11-23 implementing KMP pattern matching 108-110
algorithm.
3

1.Write Java programs that use both recursive and non-recursive functions for
implementing the linear search.

Aim: To implement the linear Search (recursive case)

Source code:

Test

static int arr[]={12,34,54,2,3};

static int class recSearch(int arr[],int l,int r,int x){

if(r<1)

return -1;

if(arr[1]==x)

return 1;

if(arr[r]==x)

return r;

return recSearch(arr,l+1,r-1,x);

public static void main(String[] args){

int x=3;

int index=recSearch(arr,0,arr.length-1,x);

if(index!=-1)

System.out.println("Element"+x+"is present at index" +index);

else

System.out.println("Element"+x+"is not present"); }}


4

OUTPUT:

Element 3 is present at index4


5

NON RECURSIVE CASE


Aim : To implement linearly search(Non recursive)

Source code:

class LinearSearch

static int search(int arr[],int n,int x)

for (int i=0;i<n;i++){

if(arr[i]==x)

return i;

return -1;

public static void main(String[] args)

int[]arr={3,4,1,7,5};

int n=arr.length;

int x=4;

int index=search(arr,n,x);

if(index == -1)

System.out.println("element is not present in the array");

else

System.out.println("Element found at position"+index);}}


6

OUTPUT: Element found at position1


7

1b.Aim : to Illustrate Recursive Binary Search

Source code:

import java.util.*;

class GSG{

int binarySearch(int arr[],int l,int r,int x){

if(r>=l&&l<=arr.length-1){

int mid=l+(r-l)/2;

if(arr[mid]==x)

return mid;

if(arr[mid]>x)

return binarySearch(arr,1,mid-1,x);

return binarySearch(arr,mid+1,r,x);}

return -1;

public static void main(String[] args){

GSG ob=new GSG();

int arr[]={2,3,4,10,40};

int n=arr.length;

int x=10;

int result=ob.binarySearch(arr,0,n-1,x);

if(result==-1)

System.out.println("element not present");

else

System.out.println("element found at index"+result); }}


8

OUTPUT:
element found at index3
9

NON RECURSIVE CASE:

Aim: To Illustrate Non- Recursive Binary Search

Source code:

class GGG{

int binarySearch(int arr[],int x){

int l=0,r=arr.length-1;

while(l<=r) {

int m=l+(r-l)/2;

if(arr[m]==x)

return m;

if(arr[m]<x)

l=m+1;

else

r=m-1;}

return -1;}

public static void main(String[] args){

GGG ob=new GGG();

int arr[]={2,3,4,10,40};

int n= arr.length;

int x=12;

int result=ob.binarySearch(arr,x);

if(result==-1)

System.out.println("element not present");

else
10

System.out.println("element found at index"+result);

}}

OUTPUT:

Element found at index0


11

2. Write Java programs to implement the following using arrays and linked lists
List ADT

a) List using Arrays

Source code:

import java.io.*;

import java.util.*;

public interface List

public void insertFirst(Object ob);

public void insertAfter(Object ob, Object pos);

public Object deleteFirst();

public Object deleteAfter(Object pos);

public boolean isEmpty();

public int size();

class ArrayList implements List {

class Node {

Object data;

int next;

Node(Object ob, int i) {

data = ob;

next = i;

}
12

int MAXSIZE;

Node list[];

int head, count;

ArrayList( int s) {

MAXSIZE = s;

list = new Node[MAXSIZE];

public void initializeList() {

for( int p = 0; p < MAXSIZE-1; p++ )

list[p] = new Node(null, p+1);

list[MAXSIZE-1] = new Node(null, -1);

public void createList(int n)

int p;

for( p = 0; p < n; p++ ){

list[p] = new Node(11+11*p, p+1);

count++;

list[p-1].next = -1;

public void insertFirst(Object item) {

if( count == MAXSIZE ) {


13

System.out.println("***List is FULL");

return; }

int p = getNode();

if( p != -1 ) {

list[p].data = item;

if( isEmpty() ) list[p].next = -1;

else list[p].next = head;

head = p;

count++;

}}

public void insertAfter(Object item, Object x) {

if( count == MAXSIZE ) {

System.out.println("***List is FULL");

return;

int q = getNode();

int p = find(x);

if( q != -1 ) {

list[q].data = item;

list[q].next = list[p].next;

list[p].next = q;

count++;

}}

public int getNode() {


14

for( int p = 0; p < MAXSIZE; p++ )

if(list[p].data == null)

return p;

return -1;

public int find(Object ob) {

int p = head;

while( p != -1){

if( list[p].data == ob ) return p;

p = list[p].next;

return -1;

public Object deleteFirst()

if( isEmpty() )

System.out.println("List is empty: no deletion");

return null;

Object tmp = list[head].data;

if( list[head].next == -1 )

head = -1;

else
15

head = list[head].next;

count--; return tmp; }

public Object deleteAfter(Object x) {

int p = find(x);

if( p == -1 || list[p].next == -1 ) {

System.out.println("No deletion");

return null; }

int q = list[p].next;

Object tmp = list[q].data;

list[p].next = list[q].next;

count--;

return tmp; }

public void display() {

int p = head;

System.out.print("\nList: [ " );

while( p != -1) {

System.out.print(list[p].data + " ");

p = list[p].next;

System.out.println("]\n");

public boolean isEmpty() {

if(count == 0) return true;

else return false;


16

public int size() {

return count;

}}

class ArrayListDemo

{public static void main(String[] args)

ArrayList linkedList = new ArrayList(10);

linkedList.initializeList();

linkedList.createList(4);

linkedList.display();

System.out.print("InsertFirst 55:");

linkedList.insertFirst(55);

linkedList.display();

System.out.print("Insert 66 after 33:");

linkedList.insertAfter(66, 33);

linkedList.display();

Object item = linkedList.deleteFirst();

System.out.println("Deleted node: " + item);

linkedList.display();

System.out.print("InsertFirst 77:");

linkedList.insertFirst(77);

linkedList.display();

item = linkedList.deleteAfter(22);
17

System.out.println("Deleted node: " + item);

linkedList.display();

System.out.println("size(): " + linkedList.size());

}}

OUTPUT :

List: [ 11 22 33 44 ]

InsertFirst 55:

List: [ 55 11 22 33 44 ]

Insert 66 after 33:

List: [ 55 11 22 33 66 44 ]

Deleted node: 55

List: [ 11 22 33 66 44 ]

InsertFirst 77:

List: [ 77 11 22 33 66 44 ]

Deleted node: 33

List: [ 77 11 22 66 44 ]

size(): 5
18

b) List Using LinkedList

Source code:

class LinkedList {

class Node{

Object data;

Node next;

Node( Object d ) {

data = d;

}}

Node head;

Node p;

int count;

public void insertFirst(Object item) {

p = new Node(item);

p.next = head;

head = p;

count++;

public void insertAfter(Object item,Object key){

p = find(key);

if( p == null )

System.out.println(key + " key is not found");

else {

Node q = new Node(item);


19

q.next = p.next;

p.next = q;

count++;

}}

public Node find(Object key){

p = head;

while( p != null ) {

if( p.data == key ) return p;

p = p.next; }

return null; }

public Object deleteFirst()

{ if( isEmpty() ) {

System.out.println("List is empty: no deletion");

return null;

Node tmp = head;

head = tmp.next;

count--;

return tmp.data;

public Object deleteAfter(Object key) {

p = find(key);

if( p == null ){

System.out.println(" key is not found");


20

return null;}

if( p.next == null) {

System.out.println("No deletion");

return null;}

else{

Node tmp = p.next;

p.next = tmp.next;

count--;

return tmp.data; }}

public void displayList() {

p = head;

System.out.print("\nLinked List: ");

while( p != null ){

System.out.print(p.data + " -> ");

p = p.next; }

System.out.println(p);

public boolean isEmpty() {

return (head == null);}

public int size(){

return count;

}}

class LinkedListDemo{

public static void main(String[] args){


21

LinkedList list = new LinkedList();

list.displayList();

list.insertFirst(55);

list.displayList();

list.insertAfter(66, 33);

list.displayList();

Object item = list.deleteFirst();

if( item != null ) {

System.out.println("deleteFirst(): " + item);

list.displayList(); }

item = list.deleteAfter(22);

if( item != null ) {

System.out.println("deleteAfter(22): " + item);

list.displayList(); }

System.out.println("size(): " + list.size());

}}

OUTPUT: Linked List : null

Linked List : 55 -> null

33 key is not found

Linked List : 55 -> null

deleteFirst(): 55

Linked List : null

key is not found

size(): 0
22

3. Write Java programs to implement the following using an array.

(a) Stack ADT


Aim: to implement stack ADT using an array import java.io.*;
Source code:

import java.io.*;

import java.util.*;

class stack<T>

ArrayList<T> A;

int top=-1;

int size;

stack(int size)

this.size = size;

this.A = new ArrayList<T>(size);

void push(T X)

if (top + 1 == size)

{
System.out.println("Stack Overflow");
}
else {
top = top+1;
if (A.size() > top)
A.set(top, X);
else
A.add(X);
23

}
}
T top()
{
if (top == -1)
{
System.out.println("Stack Underflow");
return null;
}
else
return A.get(top);
}
void pop()
{
if (top == -1)
{
System.out.println("Stack Underflow");
}
else
top--;
}
boolean empty()
{
return top == -1;
}
public String toString()
{
String Ans = "";
for (int i= 0;i< top;i++)
{
Ans += String.valueOf(A.get(i)) + "->";
}
Ans += String.valueOf(A.get(top));
return Ans;
}
}
public class GFG
{
public static void main(String[] args)
{
stack<Integer> s1 = new stack<>(3);
s1.push(10);
s1.push(20);
s1.push(30);
System.out.println("s1 after pushing 10, 20 and 30 :\n" + s1);
s1.pop();
24

System.out.println("s1 after pop :\n" + s1);


stack<String> s2 = new stack<>(3)
s2.push("hello");
s2.push("world");
s2.push("java");
System.out.println("\ns2 after pushing 3 elements :\n" + s2);
System.out.println("s2 after pushing 4th element :");
s2.push("GFG");
stack<Float> s3 = new stack<>(2);
s3.push(100.0f)
s3.push(200.0f);
System.out.println( "\ns3 after pushing 2 elements :\n" + s3);
System.out.println("top element of s3:\n"+ s3.top());
}
}

OUTPUT :

S1 after pushing 10,20 and 30 :

10->20->30

s1 after pop:

10->20

s2 after pushing 3 elements :

hello->world->java

s2 after pushing 4th element :

Stack Overflow

S3 after pushing 2 elements:

100.0->200.0

top element of s3:

200.0
25

3b. queue ADT

Aim: To implement a queue using an array


Source code :
class Queue

private static int front,rear,capacity;

private static int queue[];

Queue(int c)

front=rear=0;

capacity=c;

queue = new int[capacity];

static void queueEnqueue(int data)

if (capacity == rear)

System.out.printf("\nQueue is full\n");

return;

else

queue[rear] = data;

rear++;

}
26

return;

static void queueDequeue()

if(front == rear)

System.out.printf("\nQueue is empty\n");

return;

else

for (int i=0; i<rear-1; i++)

queue[i] = queue[i + 1];

if (rear < capacity)

queue[rear] = 0;

rear--;

return;

static void queueDisplay()

int i;
27

if (front == rear)

System.out.printf("\nQueue is Empty\n");

return;

for (i=front; i< rear; i++)

System.out.printf(" %d <-- ", queue[i]);

return;

static void queueFront()

if (front == rear)

System.out.printf("\nQueue is Empty\n");

return;

System.out.printf("\nFront Element is: %d", queue[front]);

return;

}}

public class StaticQueueinjava {

public static void main(String[] args)

{
28

Queue q = new Queue(4);

q.queueDisplay();

q.queueEnqueue(20);

q.queueEnqueue(30);

q.queueEnqueue(40);

q.queueEnqueue(50);

q.queueDisplay();

q.queueEnqueue(60);

q.queueDisplay();

q.queueDequeue();

System.out.printf("\n\nAfter two node deletion\n\n");

q.queueDisplay();

q.queueFront();

}}

OUTPUT:

Queue is Empty

20<--30<--40<--50<--

Queue is full

20<--30<--40<--50<--

After two node deletion

30<--40<--50<--

Front Element is: 30


29

4. Write a java program that reads an infix expression, converts the expression
to postfix form and then evaluates the postfix expression (use stack ADT).
Aim: To implement a java program that reads an infix expression, converts the expression to
postfix form and then evaluates the postfix expression (use stack ADT)

Source code:

import java.io.*;

class Stack

char a[]=new char[100];

int top=-1;

void push(char c)

try

a[++top]= c;

catch(StringIndexOutOfBoundsException e)

System.out.println("Stack full, no room to push, size=100");

System.exit(0);

char pop()

{
30

return a[top--];

boolean isEmpty()

return (top==-1)?true:false;

char peek()

return a[top];

public class InfixToPostfix

static Stack operators = new Stack();

public static void main(String argv[]) throws IOException

String infix;

//create an input stream object

BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in));

//get input from user

System.out.print("\nEnter the infix expression you want to convert: ");

infix = keyboard.readLine();

//output as postfix

System.out.println("Postfix expression for the given infix expression is:" + toPostfix(infix));


31

private static String toPostfix(String infix)

//converts an infix expression to postfix

char symbol;

String postfix = "";

for(int i=0;i<infix.length();++i)

//while there is input to be read

symbol = infix.charAt(i);

//if it's an operand, add it to the string

if (Character.isLetter(symbol))

postfix = postfix + symbol;

else if (symbol=='(')

//push (

operators.push(symbol);

else if (symbol==')')

//push everything back to (

while (operators.peek() != '(')

postfix = postfix + operators.pop();


32

operators.pop(); //remove '('

else

//print operators occurring before it that have greater precedence

while (!operators.isEmpty() && !(operators.peek()=='(') && prec(symbol) <=


prec(operators.peek()))

postfix = postfix + operators.pop();

operators.push(symbol);

while (!operators.isEmpty())

postfix = postfix + operators.pop();

return postfix;

static int prec(char x)

if (x == '+' || x == '-')

return 1;

if (x == '*' || x == '/' || x == '%')

return 2;

return 0;

} }
33

OUTPUT:

Enter the infix expression you want to convert: (AB+CD)/E*F

Postfix expression for the given infix expression is : ABCD+E/F*


34

5. Write Java programs to implement the following using a singly linked list. (a) Stack ADT
(b) Queue ADT
Aim:/ * Java Program to Implement Stack using Linked List*/
Source Code:
import java.util.*;

class Node

protected int data;

protected Node link;

public Node()

link = null;

data = 0;

public Node(int d,Node n)

data = d;

link = n;

public void setLink(Node n)

link = n;

public void setData(int d)

data = d;
35

public Node getLink()

return link;

public int getData()

return data;

class linkedStack

protected Node top ;

protected int size ;

public linkedStack()

top = null;

size = 0;

public boolean isEmpty()

return top == null;

public int getSize()

{
36

return size;

public void push(int data)

Node nptr = new Node (data, null);

if (top == null)

top = nptr;

else

nptr.setLink(top);

top = nptr;

size++ ;

public int pop()

if (isEmpty() )

throw new NoSuchElementException("Underflow Exception") ;

Node ptr = top;

top = ptr.getLink();

size-- ;

return ptr.getData();

public int peek()

{
37

if (isEmpty() )

throw new NoSuchElementException("Underflow Exception") ;

return top.getData();

public void display()

System.out.print("\nStack = ");

if (size == 0)

System.out.print("Empty\n");

return ;

Node ptr = top;

while (ptr != null)

System.out.print(ptr.getData()+" ");

ptr = ptr.getLink();

System.out.println();

public class LinkedStackImplement

public static void main(String[] args)

{
38

Scanner scan = new Scanner(System.in);

linkedStack ls = new linkedStack();

System.out.println("Linked Stack Test\n");

char ch;

do

System.out.println("\nLinked Stack Operations");

System.out.println("1. push");

System.out.println("2. pop");

System.out.println("3. peek");

System.out.println("4. check empty");

System.out.println("5. size");

int choice = scan.nextInt();

switch (choice)

case 1 :

System.out.println("Enter integer element to push");

ls.push( scan.nextInt() );

break;

case 2 :

try

System.out.println("Popped Element = "+ ls.pop());

catch (Exception e)
39

System.out.println("Error : " + e.getMessage());

break;

case 3 :

try

System.out.println("Peek Element = "+ ls.peek());

catch (Exception e)

System.out.println("Error : " + e.getMessage());

break;

case 4 :

System.out.println("Empty status = "+ ls.isEmpty());

break;

case 5 :

System.out.println("Size = "+ ls.getSize());

break;

case 6 :

System.out.println("Stack = ");

ls.display();

break;

default :
40

System.out.println("Wrong Entry \n ");

break;

ls.display();

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

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

OUTPUT :

Linked Stack Test

Linked Stack Operations

1. push

2. pop

3. peek

4. check empty

5. size

Enter integer element to push

20

Stack = 20

Do you want to continue (Type y or n)

Linked Stack Operations

1. push
41

2. pop

3. peek

4. check empty

5. size

Popped Element = 20

Stack = Empty

Do you want to continue (Type y or n)

Linked Stack Operations

1. push

2. pop

3. peek

4. check empty

5. size

Error : Underflow Exception

Stack = Empty

Do you want to continue (Type y or n)

Linked Stack Operations

1. push

2. pop

3. peek

4. check empty
42

5. size

Empty status = true

Stack = Empty

Do you want to continue (Type y or n)

Linked Stack Operations

1. push

2. pop

3. peek

4. check empty

5. size

Size = 0

Stack = Empty

Do you want to continue (Type y or n)

n
43

5b.Aim:/** Java Program to Implement Queue using Linked List*/

Source Code:

import java.util.*;

class Node

protected int data;

protected Node link;

public Node()

link = null;

data = 0;

public Node(int d,Node n)

data = d;

link = n;

public void setLink(Node n)

link = n;

public void setData(int d)

data = d;

}
44

public Node getLink()

return link;

public int getData()

return data;

class linkedQueue

protected Node front, rear;

public int size;

public linkedQueue()

front = null;

rear = null;

size = 0;

public boolean isEmpty()

return front == null;

public int getSize()

{
45

return size;

public void insert(int data)

Node nptr = new Node(data, null);

if (rear == null)

front = nptr;

rear = nptr;

else

rear.setLink(nptr);

rear = rear.getLink();

size++ ;

public int remove()

if (isEmpty() )

throw new NoSuchElementException("Underflow Exception");

Node ptr = front;

front = ptr.getLink();

if (front == null)

rear = null;
46

size-- ;

return ptr.getData();

public int peek() {

if (isEmpty() )

throw new NoSuchElementException("Underflow Exception");

return front.getData();

public void display()

System.out.print("\nQueue = ");

if (size == 0)

System.out.print("Empty\n");

return ;

Node ptr = front;

while (ptr != rear.getLink() )

System.out.print(ptr.getData()+" ");

ptr = ptr.getLink();

System.out.println();

}}

public class LinkedQueueImplement


47

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

linkedQueue lq = new linkedQueue();

System.out.println("Linked Queue Test\n");

char ch;

do

System.out.println("\nQueue Operations");

System.out.println("1. insert");

System.out.println("2. remove");

System.out.println("3. peek");

System.out.println("4. check empty");

System.out.println("5. size");

int choice = scan.nextInt();

switch (choice)

case 1 :

System.out.println("Enter integer element to insert");

lq.insert( scan.nextInt() );

break;

case 2 :

try

{
48

System.out.println("Removed Element = "+ lq.remove());

catch (Exception e)

System.out.println("Error : " + e.getMessage());

break;

case 3 :

try

System.out.println("Peek Element = "+ lq.peek());

catch (Exception e) {

System.out.println("Error : " + e.getMessage());

break;

case 4 :

System.out.println("Empty status = "+ lq.isEmpty());

break;

case 5 :

System.out.println("Size = "+ lq.getSize());

break;

default :

System.out.println("Wrong Entry \n ");

break;
49

lq.display();

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

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

}}

OUTPUT:

Linked Queue Test

Queue Operations

1. insert

2. remove

3. peek

4. check empty

5. size

Enter integer element to insert

24

Queue = 24

Do you want to continue (Type y or n)

Queue Operations

1. insert

2. remove

3. peek
50

4. check empty

5. size

Removed Element = 24

Queue = Empty

Do you want to continue (Type y or n)

Queue Operations

1. insert

2. remove

3. peek

4. check empty

5. size

Enter integer element to insert

34

Queue = 34
51

7. Write a Java program to implement priority queue ADT.


Aim : To implement Priority Queue ADT

Source code:

import java.util.Scanner;

class Task

String job;

int priority;

public Task(String job, int priority)

this.job = job;

this.priority = priority;

public String toString()

return "Job Name : "+ job +"\nPriority : "+ priority;

class PriorityQueue

private Task[] heap;

private int heapSize, capacity;

public PriorityQueue(int capacity)

{
52

this.capacity = capacity + 1;

heap = new Task[this.capacity];

heapSize = 0;

public void clear()

heap = new Task[capacity];

heapSize = 0;

public boolean isEmpty()

return heapSize == 0;

public boolean isFull()

return heapSize == capacity - 1;

public int size()

return heapSize;

public void insert(String job, int priority)

Task newJob = new Task(job, priority);


53

heap[++heapSize] = newJob;

int pos = heapSize;

while (pos != 1 && newJob.priority > heap[pos/2].priority)

heap[pos] = heap[pos/2];

pos /=2;

heap[pos] = newJob;

public Task remove()

int parent, child;

Task item, temp;

if (isEmpty() )

System.out.println("Heap is empty");

return null;

item = heap[1];

temp = heap[heapSize--];

parent = 1;

child = 2;

while (child <= heapSize)

{
54

if (child < heapSize && heap[child].priority < heap[child + 1].priority)

child++;

if (temp.priority >= heap[child].priority)

break;

heap[parent] = heap[child];

parent = child;

child *= 2;

heap[parent] = temp;

return item;

public class PriorityQueueTest

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

System.out.println("Priority Queue Test\n");

System.out.println("Enter size of priority queue ");

PriorityQueue pq = new PriorityQueue(scan.nextInt() );

char ch;

do

System.out.println("\nPriority Queue Operations\n");


55

System.out.println("1. insert");

System.out.println("2. remove");

System.out.println("3. check empty");

System.out.println("4. check full");

System.out.println("5. clear");

System.out.println("6. size");

int choice = scan.nextInt();

switch (choice)

case 1 :

System.out.println("Enter job name and priority");

pq.insert(scan.next(), scan.nextInt() );

break;

case 2 :

System.out.println("\nJob removed \n\n"+ pq.remove());

break;

case 3 :

System.out.println("\nEmpty Status : "+ pq.isEmpty() );

break;

case 4 :

System.out.println("\nFull Status : "+ pq.isFull() );

break;

case 5 :

System.out.println("\nPriority Queue Cleared");


56

pq.clear();

break;

case 6 :

System.out.println("\nSize = "+ pq.size() );

break;

default :

System.out.println("Wrong Entry \n ");

break;

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

ch = scan.next().charAt(0);

} while (ch == 'Y'|| ch == 'y');

}}

OUTPUT:

Priority Queue Test

Enter size of priority queue 3

Priority Queue Operations

1. insert

2. remove

3. check empty

4. check full 5. clear 6. size

Enter job name and priority job1 24

Do you want to continue (Type y or n) y


57

8. Write Java programs that use recursive and non-recursive functions to


traverse the given binary tree in (a) Preorder (b) In order and (c) Post order.
Aim:To implement Preorder_recursive function

Source Code:

import java.util.Scanner;

class BinarySearchTreeNodes

BinarySearchTreeNodes left,right;

int data;

public BinarySearchTreeNodes()

left=null;

right=null;

data=0;

public BinarysearchTreeNodes(int n)

left=null;

right=null;

data=n;

public void setLeft(BinarySearchTreeNodes n)

left=n;
58

public void setRight(BinarySearchTreeNodes n)

right=n;

public BinarySeachTreeNodesgetLeft()

return left;

public BinarySearchTreeNodesgetRight()

return right;

public void setData(int d)

data=d;

public int getData()

return data;

class BinarySearchTree

{
59

private BinarySearchTreeNodesroot;

public BinarySearchTree()

root=null;

public boolean isEmpty()

return root=null;

public void insert(int data);

root=insert(root,data);

private BinarySearchTreeNodesinsert(BinarysaearchTreeNodesnode,int data)

if(node==null)

node=new BinarySearchTreeNodes(data);

else

if(data<=node,getData())

node.left=inset(node.left,data);

else

node.right=insert(node.right,data);

return node;
60

public void preorder()

preorder(root);

private void preorder(BinarySearchTreeNodes r)

if(r!=NULL)

System.out.print(r.getData()+" ");

preorder(r.getLeft());

preorder(r.getRight());

}}}

public class Preorder_Recursive_BST

public static void main(String[] args)

scanner scan=new scanner(system.in);

BinarySearchTreebst=new BinarySearchTree();

System.out.println("Enter the first 10 elements of the tree\n");

int n=10;

for(int i=0;i<N;i++)

bst.insert(scan.nextInt());

System.out.print("\n preorder:");
61

bst.preorder();

scan.close();}]

OUTPUT:

Enter the first 10 elements of tree

12 10 11 03 15 19 01 04 70

Preorder: 12 10 3 2 1 4 11 15 19 70
62

(ii) Preorder Nonrecursive

Source Code:

import java.util.Scanner;

import java.util.Stack;

class BinarySearchTreeNode

BinarySearchTreeNode left,right;

int data;

public BinarySearchTreeNode()

left = null;

right = null;

data =0;

public BinarySearchTreeNode(int n)

left = null;

right = null;

data =n;

public void setLeft(BinarySearchTreeNode n)

left =n;

}
63

public void setRight(BinarySearchTreeNode n)

right = n;

public BinarySearchTreeNode getLeft()

return left;

public BinarySearchTreeNode getRight()

return right;

public void setData(int d)

data =d;

public int getData()

return data;

class BinarySearchTreeOperations

private BinarySearchTreeNodes root;


64

public BinarySearchTreeOperations()

root = null;

public boolean isEmpty()

return root == null;

public void insert(int data)

root = insert(root,data);

private BinarySearchTreeNodes insert(BinarySearchTreeNodes node,int data)

if(node == null)

node = new BinarySearchTreeNodes(data);

else

if(data <= node.getData())

node.left = insert(node.left,data);

else

node.right = insert(node.right,data);

return node;
65

public void preorder()

preorder(root);

private void preorder(BinarySearchTreeNodes r)

Stack<BinarySearchTreeNodes> s = new Stack<BinarySearchTreeNodes>();

s.push(r);

while(!s.empty())

r = s.pop();

System.out.print(r.data+" ");

if(r.right != null)

s.push(r.right);

if(r.left != null)

s.push(r.left);

public class Preorder_NonRecursive_BST

public static void main(String[] args)

{
66

Scanner scan = new Scanner(System.in);

BinarySearchTreeOperations bst = new BinarySearchTreeOperations();

System.out.println("enter the first 10 elements of the tree\n");

int N =10;

for(int i =0; i<N;i++)

bst.insert(scan.nextInt());

System.out.print("\n preorder:");

bst.preorder();

scan.close();

OUTPUT:

enter the first 10 elements of the tree

12 10 11 03 15 19 01 04 70 80

preorder:12 10 3 1 4 11 15 19 70 80
67

b) Aim:/*To implement Recursive Inorder*/

Source code:

import java.util.Scanner;

class BinarySearchTreeNodes

BinarySearchTreeNodes left, right;

int data;

public BinarySearchTreeNodes()

left = null;

right = null;

data = 0;

public BinarySearchTreeNodes(int n)

left = null;

right = null;

data = n;

public void setLeft(BinarySearchTreeNodes n)

left = n;
68

public void setRight(BinarySearchTreeNodes n)

right = n;

public BinarySearchTreeNodes getLeft()

return left;

public BinarySearchTreeNodes getRight()

return right;

public void setData(int d)

data = d;

public int getData()

return data;

class BinarySearchTree

{
69

private BinarySearchTreeNodes root;

public BinarySearchTree()

root = null;

public boolean isEmpty()

return root == null;

public void insert(int data)

root = insert(root, data);

private BinarySearchTreeNodes insert(BinarySearchTreeNodes node, int data)

if (node == null)

node = new BinarySearchTreeNodes(data);

else

if (data <= node.getData())

node.left = insert(node.left, data);

else

node.right = insert(node.right, data);

}
70

return node;

public void inorder()

inorder(root);

private void inorder(BinarySearchTreeNodes r)

if (r != null)

inorder(r.getLeft());

System.out.print(r.getData() + " ");

inorder(r.getRight());

public class Inorder_Recursive_BST

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

BinarySearchTree bst = new BinarySearchTree();

System.out.println("Enter the first 10 elements of the tree\n");

int N = 10;
71

for (int i = 0; i < N; i++)

bst.insert(scan.nextInt());

System.out.print("\nIn order : ");

bst.inorder();

scan.close();

OUTPUT:
Enter the first 10 elements of the tree

12 4 95 75 65 20 10 15 14 45

In order : 4 10 12 14 15 20 45 65 75 95
72

(ii):To implement Non Recursive Inorder

Source code:

import java.util.Scanner;

import java.util.Stack;

class BinarySearchTreeNode

BinarySearchTreeNode left, right;

int data;

public BinarySearchTreeNode()

left = null;

right = null;

data = 0;

public BinarySearchTreeNode(int n)

left = null;

right = null;

data = n;

public void setLeft(BinarySearchTreeNode n)

left = n;

}
73

public void setRight(BinarySearchTreeNode n)

right = n;

public BinarySearchTreeNode getLeft()

return left;

public BinarySearchTreeNode getRight()

return right;

public void setData(int d)

data = d;

public int getData()

return data;

class BinarySearchTreeOperations

private BinarySearchTreeNodes root;


74

public BinarySearchTreeOperations()

root = null;

public boolean isEmpty()

return root == null;

public void insert(int data)

root = insert(root, data);

private BinarySearchTreeNodes insert(BinarySearchTreeNodes node, int data)

if (node == null)

node = new BinarySearchTreeNodes(data);

else

if (data <= node.getData())

node.left = insert(node.left, data);

else

node.right = insert(node.right, data);

return node;
75

public void inorder()

inorder(root);

private void inorder(BinarySearchTreeNodes r)

if (r == null)

return;

Stack<BinarySearchTreeNodes> stack = new Stack<BinarySearchTreeNodes>();

while (!stack.isEmpty() || r != null)

if (r != null)

stack.push(r);

r = r.left;

} else

r = stack.pop();

System.out.print(r.data + " ");

r = r.right;

}
76

public class Inorder_NonRecursive_BST

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

BinarySearchTreeOperations bst = new BinarySearchTreeOperations();

System.out.println("Enter the first 10 elements of the tree\n");

int N = 10;

for (int i = 0; i < N; i++)

bst.insert(scan.nextInt());

System.out.print("\nIn order : ");

bst.inorder();

scan.close();

OUTPUT:
Enter the first 10 elements of the tree

11 10 20 26 29 78 98 95 45 13

In order : 10 11 13 20 26 29 45 78 95 98
77

iii) post order(recursive case)

source code

import java.util.Scanner;

class BinarySearchTreeNodes

BinarySearchTreeNodes left, right;

int data;

public BinarySearchTreeNodes()

left = null;

right = null;

data = 0;

public BinarySearchTreeNodes(int n)

left = null;

right = null;

data = n;

public void setLeft(BinarySearchTreeNodes n)

left = n;

public void setRight(BinarySearchTreeNodes n)


78

right = n;

public BinarySearchTreeNodes getLeft()

return left;

public BinarySearchTreeNodes getRight()

return right;

public void setData(int d)

data = d;

public int getData()

return data;

class BinarySearchTree

private BinarySearchTreeNodes root;


79

public BinarySearchTree()

root = null;

public boolean isEmpty()

return root == null;

public void insert(int data)

root = insert(root, data);

private BinarySearchTreeNodes insert(BinarySearchTreeNodes node, int data)

if (node == null)

node = new BinarySearchTreeNodes(data);

else

if (data <= node.getData())

node.left = insert(node.left, data);

else

node.right = insert(node.right, data);

return node;
80

public void postorder()

postorder(root);

private void postorder(BinarySearchTreeNodes r)

if (r != null)

postorder(r.getLeft());

postorder(r.getRight());

System.out.print(r.getData() + " ");

public class Postorder_Recursive_BST

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

BinarySearchTree bst = new BinarySearchTree();

System.out.println("Enter the first 10 elements of the tree\n");

int N = 10;

for (int i = 0; i < N; i++)


81

bst.insert(scan.nextInt());

System.out.print("\nPost order : ");

bst.postorder();

scan.close();

OUTPUT:
Enter the first 10 elements of the tree

12 10 4 3 16 15 12 19 3 1

Post order : 1 3 3 4 12 10 15 19 16 12
82

*Postorder(non recursive case)

Source code:

import java.util.Scanner;

import java.util.Stack;

class BinarySearchTreeNode

BinarySearchTreeNode left, right;

int data;

public BinarySearchTreeNode()

left = null;

right = null;

data = 0;

public BinarySearchTreeNode(int n)

left = null;

right = null;

data = n;

public void setLeft(BinarySearchTreeNode n)

left = n;

}
83

public void setRight(BinarySearchTreeNode n)

right = n;

public BinarySearchTreeNode getLeft() {

return left;

public BinarySearchTreeNode getRight()

return right;

public void setData(int d)

data = d;

public int getData()

return data;

class BinarySearchTreeOperations

private BinarySearchTreeNodes root;

public BinarySearchTreeOperations()
84

root = null;

public boolean isEmpty()

return root == null;

public void insert(int data)

root = insert(root, data);

private BinarySearchTreeNodes insert(BinarySearchTreeNodes node, int data)

if (node == null)

node = new BinarySearchTreeNodes(data);

else

if (data <= node.getData())

node.left = insert(node.left, data);

else

node.right = insert(node.right, data);

return node;

}
85

public void postorder()

postorder(root);

private void postorder(BinarySearchTreeNodes r)

if (root == null)

return;

final Stack<BinarySearchTreeNodes> stack = new Stack<BinarySearchTreeNodes>();

BinarySearchTreeNodes node = root;

while (!stack.isEmpty() || node != null)

while (node != null)

if (node.right != null)

stack.add(node.right);

stack.add(node);

node = node.left;

node = stack.pop();

if (node.right != null && !stack.isEmpty()

&& node.right == stack.peek())

BinarySearchTreeNodes nodeRight = stack.pop();


86

stack.push(node);

node = nodeRight;

} else

System.out.print(node.data + " ");

node = null;

public class Postorder_NonRecursive_BST

public static void main(String[] args)

Scanner scan = new Scanner(System.in);

BinarySearchTreeOperations bst = new BinarySearchTreeOperations();

System.out.println("Enter the first 10 elements of the tree\n");

int N = 10;

for (int i = 0; i < N; i++)

bst.insert(scan.nextInt());

System.out.print("\nPost order : ");

bst.postorder();

scan.close();

}
87

OUTPUT:

Enter the first 10 elements of the tree

12 4 13 7 4 89 78 98 45 20

Post order : 4 7 4 20 45 78 98 89 13 12
88

9)Write a java program that displays node values in a level order


traversal(Traverse the tree one level at a time, starting at the root node )for a
binary tree.

Aim: To display node values in a level order traversal for a binary tree.

Source Code:

class Node

int data;

Node left,right;

public Node(int item)

data=item;

left=right=null;

class BinaryTree

Node root;

public BinaryTree()

root=null;

void printLevelOrder()
89

int h=height(root);

int i;

for(i=1;i<=h;i++)

printCurrentLevel(root,i);

int height(Node root)

if(root==null)

return 0;

else

int lheight=height(root.left);

int rheight=height(root.right);

if(lheight>rheight)

return(lheight+1);

else

return(rheight+1);

void printCurrentLevel(Node root,int level)

if(root==null)

return;
90

if(level==1)

System.out.print(root.data+"");

else if(level>1)

printCurrentLevel(root.left,level-1);

printCurrentLevel(root.right,level-1);

public static void main(String args[])

BinaryTree tree=new BinaryTree();

tree.root=new Node(1);

tree.root.left=new Node(2);

tree.root.right=new Node(3);

tree.root.left.left=new Node(4);

tree.root.left.right=new Node(5);

System.out.println("Level order traversal of"+"binary tree is");

tree.printLevelOrder();

}}

OUTPUT:

Level order traversal of binary tree is

12345
91

10.Write a Java program to perform the following operations:

a) Construct a binary search tree of elements.

Aim: To Construct a binary search tree of elements.

Source Code:

import java.util.*;

class Bstnode

Bstnode rc,lc;

Bstnode root;

int data;

Bstnode()

data=0;

rc=lc=null;

Bstnode(int item)

data=item;

lc=rc=null;

Bstnode[] search(int key)

Bstnode par,ptr;
92

Bstnode b[]=new Bstnode[2];

ptr=root;

par=null;

while(ptr!=null)

if(ptr.data==key)

b[0]=par;

b[1]=ptr;

return b;

else if(ptr.data<key)

par=ptr;

ptr=ptr.rc;

else

par=ptr;

ptr=ptr.lc;

b[0]=par;b[1]=ptr;

return b;
93

void insert(int item)

Bstnode arr[]=new Bstnode[2];

Bstnode nn = new Bstnode(item);

arr=search(item);

if(root!=null)

Bstnode par=arr[0];

Bstnode ptr=arr[1];

if(ptr!=null)

System.out.println("key already existed");

else

if(par.data<item)

par.rc=nn;

else

par.lc=nn;

else

root = nn;

void inorder(Bstnode ptr)


94

if(ptr!=null)

inorder(ptr.lc);

System.out.println(ptr.data);

inorder(ptr.rc);

void preorder(Bstnode ptr)

if(ptr!=null)

System.out.println(ptr.data);

inorder(ptr.lc);

inorder(ptr.rc);

void postorder(Bstnode ptr)

if(ptr!=null)

inorder(ptr.lc);

inorder(ptr.rc);

System.out.println(ptr.data);
95

int deleteleaf(Bstnode par,Bstnode ptr)

if(par!=null)

if(par.lc==ptr)

par.lc=null;

else

par.rc=null;

else

root=null;

return ptr.data;

int delete1childnode(Bstnode par,Bstnode ptr)

if(par!=null)

if(par.lc==ptr)

if(ptr.lc==null)

par.lc=ptr.rc;

else
96

par.lc=ptr.lc;

else if(par.rc==ptr)

if(ptr.lc==null)

par.rc=ptr.rc;

else

par.rc=ptr.lc;

else

if(ptr.rc!=null)

root=ptr.rc;

else

root=ptr.lc;

return ptr.data;

int delete2childnode(Bstnode par, Bstnode ptr)

Bstnode ptr1=ptr.rc;

Bstnode par1=null;

while(ptr1.lc!=null)
97

par1=ptr1;

ptr1=ptr1.lc;

if(par1!=null)

if(ptr1.rc!=null)

par1.lc=ptr1.rc;

else

par1.lc=null;

ptr1.lc=ptr.lc;

ptr1.rc=ptr.rc;

else // if par1=null

ptr1.lc = ptr.lc;

if(par!=null)

if(par.lc==ptr)

par.lc=ptr1;

else

par.rc=ptr1;

else

root=ptr1;
98

return ptr.data;

int deletenode(int item)

Bstnode ptr=root,par=null;

boolean flag=false;

int k;

while(ptr!=null&&flag==false)

if(item<ptr.data)

par=ptr;

ptr=ptr.lc;

else if(item>ptr.data)

par=ptr;

ptr=ptr.rc;

else

ptr.data=item;

flag=true;

}
99

if(flag==false)

System.out.println("item not found hence can not delete");

return -1;

if(ptr.lc==null&&ptr.rc==null)

k=deleteleaf(par,ptr);

else if(ptr.lc!=null&&ptr.rc!=null)

k=delete2childnode(par,ptr);

else

k=delete1childnode(par,ptr);

return k;

public static void main(String saichandra[])

Bstnode b=new Bstnode();

Scanner s=new Scanner (System.in);

int ch;

do

System.out.println("1.insert");

System.out.println("2.delete");

System.out.println("3.search");
100

System.out.println("4.inorder");

System.out.println("5.preorder");

System.out.println("6.postorder");

System.out.print("enter ur choice:");

ch=s.nextInt();

switch(ch)

case 1:System.out.print("enter element:");

int n=s.nextInt();

b.insert(n);

break;

case 2:if(b.root!=null)

System.out.print("enter element:");

int n1=s.nextInt();

int res=b.deletenode(n1);

if(res!=-1)

System.out.println("deleted element is:"+res);

else

System.out.println("no elements in tree");

break;

case 3:if(b.root!=null)

{
101

System.out.println("enter search element");

int key=s.nextInt();

Bstnode search1[]=new Bstnode[2];

search1=b.search(key);

if(search1[1]!=null)

System.out.println("key is found");

else

System.out.println("key not found");

if(search1[0]!=null)

if(search1[1]!=null)

System.out.println("parent of the searched element is:"+search1[0].data);

else

System.out.println("key is root no parent exist");

else

System.out.println("no elements in tree");

break;

case 4:if(b.root!=null)

b.inorder(b.root);

else

System.out.println("no elements in tree");

break;
102

case 5:if(b.root!=null)

b.preorder(b.root);

else

System.out.println("no elements in tree");

break;

case 6:if(b.root!=null)

b.postorder(b.root);

else

System.out.println("no elements in tree");

break;

}while(ch!=0);

OUTPUT:

1.insert

2.delete

3.search

4.inorder

5.preorder

6.postorder

enter ur choice:3

no elements in tree
103

11. Write Java programs for the implementation of bfs and dfs for a given graph.
Aim: to implement bfs for a given graph

Source code:

import java.io.*;

import java.util.*;

class Graph1

private int V;

private LinkedList<Integer> adj[];

@SuppressWarnings("unchecked")Graph1(int v)

V=v;

adj=new LinkedList[v];

for(int i=0;i<v;++i)

adj[i]=new LinkedList();

void addEdge(int v,int w)

adj[v].add(w);

void BFS(int s)

boolean visited[]=new boolean[V];


104

LinkedList<Integer>queue=new LinkedList<Integer>();

visited[s]=true;

queue.add(s);

while(queue.size()!=0)

s=queue.poll();

System.out.print(s+"");

Iterator<Integer>i=adj[s].listIterator();

while(i.hasNext())

int n=i.next();

if(!visited[n])

visited[n]=true;

queue.add(n);

public static void main(String args[])

Graph1 g=new Graph1(4);

g.addEdge(0,1);

g.addEdge(0,2);
105

g.addEdge(1,2);

g.addEdge(2,0);

g.addEdge(2,3);

g.addEdge(3,3);

System.out.println("Following is Breadth First Taversal"+"(starting from vertex2)");

g.BFS(2);

OUTPUT:

Following is Breadth First Taversal(starting from vertex2)

2031
106

12. Write Java programs for implementing the following sorting methods: (a)
Bubble sort (b) Selection sort (c) Insertion sort (d) Radix sort

Aim: // Java program for implementation of Bubble Sort//

Source code

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();

}
107

public static void main(String args[])

BubbleSort ob = new BubbleSort();

int arr[] ={ 64,34,25,12,22,11,90};

ob.bubblesort(arr);

System.out.println("sorted array");

ob.PrintArray(arr);

OUTPUT:
sorted array

11 12 22 25 34 64 90
108

b) Aim: // Java program for implementation of Selection Sort//

Source code:

import java.io.*;

import java.util.*;

class SelectionSort

void sort(int arr[]){

int n=arr.length;

for(int i=0;i<n-1;i++){

int min_idx=i;

for(int j=i+1;j<n;j++)

if(arr[j]<arr[min_idx])

min_idx=j;

int temp=arr[min_idx];

arr[min_idx]=arr[i];

arr[i]=temp;

}}

void printArray(int arr[]){

int n=arr.length;

for(int i=0;i<n;++i)

System.out.println(arr[i]+" ");

System.out.println();

public static void main(String args[]){


109

SelectionSort ob=new SelectionSort();

int arr[]={64,25,12,22,11};

ob.sort(arr);

System.out.println("SAorted array");

ob.printArray(arr);

OUTPUT: Sorted array

11

12

22

25

64
110

c)Aim: Java program for implementation of Insertion Sort

Source code:

import java.io.*;

import java.util.*;

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;

for(int i=0;i<n;++i)

System.out.print(arr[i]+" ");

System.out.println();

public static void main(String[] args)


111

int arr[]={12,11,13,5,6};

InsertionSort ob=new InsertionSort();

ob.sort(arr);

printArray(arr);

}}

OUTPUT:

5 6 11 12 13
112

d) Aim: Java program for implementation of Radix Sort

Source code:

import java.io.*;

import java.util.*;

class Radix{

static int getMax(int arr[],int n)

int mx=arr[0];

for(int i=1;i<n;i++)

if(arr[i]>mx)

mx=arr[i];

return mx;

static void countSort(int arr[],int n,int exp){

int output[]=new int[n];

int i;

int count[]=new int[10];

Arrays.fill(count,0);

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

count[(arr[i]/exp)%10]++;

for(i=1;i<10;i++)

count[i]+=count[i-1];

for(i=n-1;i>=0;i--){

output[count[(arr[i]/exp)%10]-1]=arr[i];
113

count[(arr[i]/exp)%10]--;

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

arr[i]=output[i];

static void radixSort(int arr[],int n){

int m=getMax(arr,n);

for(int exp=1;m/exp>0;exp*=10)

countSort(arr,n,exp);

static void print(int arr[],int n){

for(int i=0;i<n;i++)

System.out.println(arr[i]+" ");

public static void main(String args[]){

int arr[]={170,45,75,90,802,24,2,66};

int n=arr.length;

radixSort(arr,n);

print(arr,n);

}}

OUTPUT:

24

45
114

66

75

90

170

802
115

13. Write a Java program for implementing KMP pattern matching algorithm.

Aim:To implement KMP pattern matching algorithm

Source code:

class KMP_String_Matching

void KMPSearch(String pat,String txt)

int M=pat.length();

int N=txt.length();

int lps[]=new int[M];

int j=0;

computeLPSArray(pat,M,lps);

int i=0;

while((N-i)>=(M-j))

if(pat.charAt(j)==txt.charAt(i)){

j++;

i++;

if(j==M){

System.out.println("Found pattern"+"at index"+(i-j));

j=lps[j-1];

}
116

else if(i<N && pat.charAt(j)!=txt.charAt(i))

if(j!=0)

j=lps[j-1];

else

i=i+1;

void computeLPSArray(String pat,int M,int lps[])

int len=0;

int i=1;

lps[0]=0;

while(i<M){

if(pat.charAt(i)==pat.charAt(len))

len++;

lps[i]=len;

i++;

else

if(len!=0){
117

len=lps[len-1];}

else{

lps[i]=len;

i++;

public static void main(String args[])

String txt="ABABDABACDABABCABAB";

String pat="ABABCABAB";

new KMP_String_Matching().KMPSearch(pat,txt);

OUTPUT:

Found pattern at index 10

You might also like