You are on page 1of 52

DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

1. Write Java programs that use both recursive and non-recursive functions for
implementing the following searching methods.

a) Binary search b) Linear search

AIM: To write a Java program that uses both recursive and non-recursive functions for implementing the following
searching methods i.e Linear search and Binary search.

DESCRIPTION:

Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In Linear
search, we simply traverse the list completely and match each element of the list with the item whose
location is to be found. If the match is found, then the location of the item is returned; otherwise, the
algorithm returns NULL. It is widely used to search an element from the unordered list, i.e., the list in
which items are not sorted. The worst-case time complexity of linear search is O(n). Binary search: Binary
search is the search technique that works efficiently on sorted lists. Hence, to search an element into some
list using the binary search technique, we must ensure that the list is sorted. Binary search follows the
divide and conquer approach in which the list is divided into two halves, and the item is compared with the
middle element of the list. If the match is found then, the location of the middle element is returned.
Otherwise, we search into either of the halves depending upon the result produced through the match.

(a) Binary Search Method:

SOURCE CODE:

class RecursiveBinarySearch{

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[]){

RecursiveBinarySearch ob = new RecursiveBinarySearch();

20JG1A0431 Page 1 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
int arr[] = { 2, 3, 4, 10, 40 };

int n = arr.length;

int x = 10;

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

if (result == -1)

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

Else

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


OUTPUT:

SOURCE CODE:

//Binary Search in java using without recursion

class BinarySearch

public static void binarySearch(int arr[],int first,int last,int key) {

int mid=(first+last)/2;

while(first <= last){

if(arr[mid]<key){

first=mid+1;

else if(arr[mid]==key){

System.out.println("Element is found at index:"+mid);

break;

else{

20JG1A0431 Page 2 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
last=mid-1;

mid=(first+last)/2;

if(first>last){

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

}}

public static void main(String args[]){

int arr[]={10,20,30,40,50};

int key=30;

int last=arr.length-1;

binarySearch(arr,0,last,key);

}}
OUTPUT :

(b) Linear Search Method:

SOURCE CODE:

class RecursiveLinearSearch{

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

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

if (r < l)

return -1;

if (arr[l] == x)

return l;

if (arr[r] == x)

20JG1A0431 Page 3 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
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");

}}
OUTPUT:

SOURCE CODE:

class LinearSearch{

static int linearSearch(int a[], int n, int val) {

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

if (a[i] == val)

return i+1;

return -1;

public static void main(String args[]) {

int a[] = {55, 29, 10, 40, 57, 41, 20, 24, 45}; // given array

int val = 10; // value to be searched

20JG1A0431 Page 4 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
int n = a.length; // size of array

int res = linearSearch(a, n, val); // Store result

System.out.println();

System.out.print("The elements of the array are - ");

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

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

System.out.println();

System.out.println("Element to be searched is - " + val);

if (res == -1)

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

else

System.out.println("Element is present at " + res +" position of array");

} }
OUTPUT:

20JG1A0431 Page 5 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

2. Write Java programs to implement the List ADT using arrays and linked lists.
AIM: To implement the List ADT using arrays and linked list.

DESCRIPTION:
A Linked List stores the elements of the 'List' in separate memory locations and we keep track of the memory
locations as part of the information stored with an element (called a node). – A 'node' in a Linked List contains
the data value as well as the address of the next node.

2.A write a java program to implement the List ADT using Arrays

SOURCE CODE:

import java.util.*;

public class ALExample {

public static void main(String[] args) {

List<String> l = new ArrayList(); //List Implementation

l.add("Sam"); //adding objects to list

l.add("Sandy");

l.add("Joe");

l.add("Arya");

l.add("Nik");

System.out.println("List objects are: " +l); // printing the list

l.remove("Nik"); //removing objects from list

System.out.println("After Removing Nik, List Objects are" +l);

OUTPUT:

20JG1A0431 Page 6 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
2.B write a java program to implement the List ADT using linked lists

SOURCE CODE:

import java.util.LinkedList;

class Main

public static void main(String[] args) {

LinkedList<String> languages = new LinkedList();

languages.add("Python");

languages.add("Java");

languages.add("JavaScript");

System.out.println("LinkedList: " + languages);

String str = languages.get(1);

System.out.print("Element at index 1: " + str);

languages.add("Java");

languages.add("Python");

languages.add("JavaScript");

languages.add("Java");

System.out.println("LinkedList: " + languages);

languages.set(3, "Kotlin");

System.out.println("Updated LinkedList: " + languages);

String str1 = languages.remove(1);

System.out.println("Removed Element: " + str1);

System.out.println("Updated LinkedList: " + languages);

20JG1A0431 Page 7 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
OUTPUT:

20JG1A0431 Page 8 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

3. Write a Java program to implement the following using an array.

a) StackADT b) QueueADT
AIM:To implement java program of following using an array i.e StackADT and QueueADT.

DESCRIPTION:

A stack is an ordered data structure belonging to the Java Collection Framework. In this collection, the
elements are added and removed from one end only. The end at which the elements are added and
removed is called “Top of the Stack”. As addition and deletion are done only at one end, the first element
added to the stack happens to be the last element removed from the stack. Thus stack is called a LIFO
(Last-in, First-out) data structure. Push: Adds an element to the stack. As a result, the value of the top is
incremented.

Pop: An element is removed from the stack. After the pop operation, the value of the top is
decremented.

Peek: This operation is used to look up or search for an element. The value of the top is not modified.
Queue ADT: Queue is also an abstract data type or a linear data structure, just like stack data structure, in
which the first element is inserted from one end called the REAR(also called tail), and the removal of
existing element takes place from the other end called as FRONT(also called head). This makes queue as
FIFO(First in First Out) data structure, which means that element inserted first will be removed first.
Queue can be implemented by using arrays as well as link list

(a) StackADT:
SOURCECODE:

import java.util.*;

class Stack

int top; //define top of stack

int maxsize = 5; //max size of the stack

int[] stack_arry = new int[maxsize]; //define array that will hold stack elements

Stack()

{ //stack constructor; initially top = -1

top = -1;

boolean isEmpty()

{ //isEmpty () method

return (top < 0);

20JG1A0431 Page 9 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
}

boolean push (int val){

if(top == maxsize-1){

System.out.println("Stack Overflow !!");

return false; }

else{

top++;

stack_arry[top]=val;

return true;

} }

boolean pop ()

{ //pop () method

if (top == -1) {

System.out.println("Stack Underflow !!");

return false;

else {

System.out.println("\nItem popped: " + stack_arry[top--]);

return true;

} }

void display () { //print the stack elements

System.out.println("Printing stack elements .... ");

for(int i = top; i>=0;i--) {

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

} } }

public class StackADT{

public static void main(String[] args){

Stack stck = new Stack();

System.out.println("Initial Stack Empty : " + stck.isEmpty());

stck.push(10);

20JG1A0431 Page 10 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
stck.push(20);

stck.push(30);

stck.push(40);

System.out.println("After Push Operation...");

stck.display();

stck.pop();

stck.pop();

System.out.println("After Pop Operation...");

stck.display();

}}

OUTPUT:

(b) QueueADT:
SOURCECODE:
class Queue {

private static int front, rear, capacity;

private static int queue[];

Queue(int size){

front = rear = 0;

capacity = size;

queue = new int[capacity];

20JG1A0431 Page 11 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
}
static void queueEnqueue(int item) {

if (capacity == rear) {

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

return;

else {

queue[rear] = item;

rear++;

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;

if (front == rear) {

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

return;

20JG1A0431 Page 12 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
}
for (i = front; i < rear; i++) {

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

return;

static void queueFront() {

if (front == rear) {

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

return;

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

return;

}}

public class QueueADT {

public static void main(String[] args) {

Queue q = new Queue(4);

System.out.println("Initial Queue:");

q.queueDisplay();

q.queueEnqueue(10);

q.queueEnqueue(30);

q.queueEnqueue(50);

q.queueEnqueue(70);

System.out.println("Queue after Enqueue Operation:");

q.queueDisplay();

q.queueFront();

q.queueEnqueue(90);

q.queueDisplay();

q.queueDequeue();

q.queueDequeue();

System.out.printf("\nQueue after two dequeue operations:");

20JG1A0431 Page 13 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
q.queueDisplay();

q.queueFront();

} }

OUTPUT:

20JG1A0431 Page 14 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

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 the java program that reads an infix expression, coverts the expression to postfix form
and then evaluate the postfix expression.

DESCRIPTION:

To convert infix expression to postfix expression, we will use the stack data structure. By
scanning the infix expression from left to right, when we will get any operand, simply add them to
the postfix form, and for the operator and parenthesis, add them in the stack maintaining the
precedence of them.

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

return a[top--];

boolean isEmpty() {

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

char peek() {

return a[top];

} }

20JG1A0431 Page 15 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
public class InfixToPostfix {

static Stack operators = new Stack();

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

String infix;

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

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

infix = keyboard.readLine();

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

private static String toPostfix(String infix) {

char symbol;

String postfix = "";

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

symbol = infix.charAt(i);

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

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

else

//print operators occurring before it that have greater precedence {

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

20JG1A0431 Page 16 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
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;

} }

OUTPUT:

20JG1A0431 Page 17 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

5. Write Java programs to implement the following using a singly linked list.
(a) Stack ADT (b) Queue ADT
AIM: To implement the Stack ADT and queue ADT using singly linked list.

DESCRIPTION:

Linked List is an Abstract Data Type (ADT) that holds a collection of Nodes, the nodes can be accessed in
a sequential way. When the Nodes are connected with only the next pointer the list is called Singly Linke
List. A linked list is a series of connected nodes, where each node is a data structure.
stack is a linked list that allows insertion / removal only from its tail, and. queue is a linked list that allows
insertion only at its tail and removal only from its head.
a)Stack ADT:
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;

public Node getLink() {

return link;

20JG1A0431 Page 18 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
}

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

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

20JG1A0431 Page 19 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
Node ptr = top;

top = ptr.getLink();

size-- ;

return ptr.getData();

public int peek(){

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){

Scanner scan = new Scanner(System.in);

linkedStack ls = new linkedStack();

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

char ch;

do {

20JG1A0431 Page 20 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
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) {

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

20JG1A0431 Page 21 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
break;

case 5 :

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

break;

case 6 :

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

ls.display();

break;

default :

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:

20JG1A0431 Page 22 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
(b)Queue ADT:

SOURCE CODE:
// Java program for linked-list implementation of queue

class QNode

{ int key;

QNode next ;

public QNode(int key){

this.key = key;

this.next = null ;

}}

class Queue

{ QNode front, rear;

public Queue ()

{ this.front = this.rear = null;

void enqueue (int key)

{ QNode temp = new QNode(key);

if (this.rear == null)

{ this.front = this.rear = temp;

return;

this.rear.next = temp;

this.rear = temp;

void dequeue (){

if (this.front == null)

return;

QNode temp = this.front;

this.front = this.front.next;

if (this.front == null)

this.rear = null;

20JG1A0431 Page 23 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
}}

public class QADTLL{

public static void main(String[] args) {

Queue q = new Queue();

q.enqueue(10);

q.enqueue(20);

q.dequeue();

q.dequeue();

q.enqueue(30);

q.enqueue(40);

q.enqueue(50);

q.dequeue();

System.out.println("Queue Front : " + q.front.key); System.out.println("Queue Rear : " + q.rear.key); }}

OUTPUT:

20JG1A0431 Page 24 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

6)Write Java programs to implement the deque (double ended queue) ADT using
(a) Array (b) Doubly linked list.
AIM: To implement the deque (double ended queue) ADT using Array and Doubly linked list.

DESCRIPTION:
A deque or double-ended queue is an ordered group of items that functions similarly to a queue. It has two ends, a
front and a back, and the items in the collection remain in place,while the Deque can mimic many of the properties
of stacks and queues, it doesn't require the LIFO and FIFO orderings that those data structures enforce. It is up to
you to use the addition and removal operations consistently.

o Get the front item from the deque


o Get the rear item from the deque
o Check whether the deque is full or not
o Checks whether the deque is empty or not

SOURCE CODE:(a)

import java.util.*;

class Book

int id;

String name,author,publisher;

int quantity;

public Book(int id, String name, String author, String publisher, int quantity)

this.id = id;

this.name = name;

this.author = author;

this.publisher = publisher;

this.quantity = quantity;

} }

public class ArrayDequeExample{

public static void main(String[] args){

20JG1A0431 Page 25 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
ArrayDeque<Book> set=new ArrayDeque<Book>();

//Creating Books

Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);

Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

Book b3=new Book(103,"Operating System","Galvin","Wiley",6);

set.add(b1);

set.add(b2);

set.add(b3);

for(Book b:set)

System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);

} } }

OUTPUT:

Source code: (b)

public class LinkedListDeque {

private Node head;

private Node tail;

static class Node{

int i;

Node next;

Node prev;

Node(int i){

20JG1A0431 Page 26 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
this.i = i;

public void displayData(){

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

}}

public LinkedListDeque(){

this.head = null;

this.tail = null;

public boolean isEmpty(){

return head == null;

public void insertFirst(int i){

Node newNode = new Node(i);

if(isEmpty()){

tail = newNode;

}else{

head.prev = newNode;

newNode.next = head;

head = newNode;

public void insertLast(int i){

Node newNode = new Node(i);

if(isEmpty()){

head = newNode;

20JG1A0431 Page 27 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

}else{

tail.next = newNode;

newNode.prev = tail;

tail = newNode;

public Node removeFirst(){

if(head == null){

throw new RuntimeException("Deque is empty");

Node first = head;

if(head.next == null){

tail = null;

}else{

head.next.prev = null;

head = head.next;

return first;

public Node removeLast(){

if(tail == null){

throw new RuntimeException("Deque is empty");

Node last = tail;

if(head.next == null){

head = null;

20JG1A0431 Page 28 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

}else{

tail.prev.next = null;

tail = tail.prev;

return last;

public int getFirst(){

if(isEmpty()){

throw new RuntimeException("Deque is empty");

return head.i;

public int getLast(){

if(isEmpty()){

throw new RuntimeException("Deque is empty");

return tail.i;

public void displayForward(){

Node current = head;

while(current != null){

current.displayData();

current = current.next;

System.out.println("");

20JG1A0431 Page 29 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
public void displayBackward(){

Node current = tail;

while(current != null){

current.displayData();

current = current.prev;

System.out.println("");

public static void main(String[] args) {

LinkedListDeque deque = new LinkedListDeque();

deque.insertFirst(2);

deque.insertFirst(1);

deque.insertLast(3);

deque.insertLast(4);

deque.displayForward();

Node node = deque.removeFirst();

System.out.println("Node with value "+ node.i + " deleted");

deque.displayForward();

System.out.println("First element in the deque " + deque.getFirst());

System.out.println("Last element in the deque " + deque.getLast());

}}

Output:

20JG1A0431 Page 30 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

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


AIM: To implement priority queue ADT using a java program.

DESCRIPTION:

Priority Queue is an abstract data type that is similar to a queue, and every element has some
priority value associated with it. The priority of the elements in a priority queue determines the order
in which elements are served (i.e., the order in which they are removed).

SOURCE CODE:

// Java code to implement Priority Queue

import java.util.* ;

class Priorityqueue

static class Node {

int data;

int priority;

Node next;

static Node node = new Node();

static Node newNode(int d, int p) {

Node temp = new Node();

temp.data = d;

temp.priority = p;

temp.next = null;

return temp; }

static int peek(Node head){

return (head).data;

static Node pop(Node head){

20JG1A0431 Page 31 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
Node temp = head;

(head) = (head).next;

return head;

static Node push(Node head, int d, int p) {

Node start = (head);

Node temp = newNode(d, p);

if ((head).priority < p) {

temp.next = head;

(head) = temp; }

else {

while (start.next != null &&

start.next.priority > p) {

start = start.next;

temp.next = start.next; start.next = temp;

return head;

static int isEmpty(Node head){

return ((head) == null)?1:0;

public static void main(String args[]) {

Node pq = newNode(4, 1);

pq =push(pq, 5, 2);

pq =push(pq, 6, 3);

20JG1A0431 Page 32 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
pq =push(pq, 7, 0);

while (isEmpty(pq)==0){

System.out.printf("%d ", peek(pq)); pq=pop(pq);

}}}

OUTPUT:

20JG1A0431 Page 33 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

(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 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.

DESCRIPTION:
1. .

SOURCE CODE:

class Node {

public int value;

public Node left, right;

public Node(int element)

value = element;

left = right = null;

} }

class Tree {

Node root; /* root of the tree */

Tree() { root = null; }

/*function to print the nodes of given binary in Preorder*/

void traversePreorder(Node node)

if (node == null)

return;

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

traversePreorder(node.left);

20JG1A0431 Page 34 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
traversePreorder(node.right);

/*function to print the nodes of given binary in Inorder*/

void traverseInorder(Node node)

if (node == null)

return;

traverseInorder(node.left);

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

traverseInorder(node.right);

/*function to print the nodes of given binary in Postorder*/

void traversePostorder(Node node)

if (node == null)

return;

traversePostorder(node.left);

traversePostorder(node.right);

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

void traversePreorder() { traversePreorder(root); }

void traverseInorder() { traverseInorder(root); }

void traversePostorder() { traversePostorder(root); }

public static void main(String args[])

Tree pt = new Tree();

pt.root = new Node(36);

20JG1A0431 Page 35 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
pt.root.left = new Node(26);

pt.root.right = new Node(46);

pt.root.left.left = new Node(21);

pt.root.left.right = new Node(31);

pt.root.left.left.left = new Node(11);

pt.root.left.left.right = new Node(24);

pt.root.right.left = new Node(41);

pt.root.right.right = new Node(56);

pt.root.right.right.left = new Node(51);

pt.root.right.right.right = new Node(66);

System.out.println();

System.out.println("The Preorder traversal of given binary tree is - ");

pt.traversePreorder();

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

System.out.println("The Inorder traversal of given binary tree is - ");

pt.traverseInorder();

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

System.out.println("The Postorder traversal of given binary tree is - ");

pt.traversePostorder();

System.out.println();

} }

OUTPUT:

20JG1A0431 Page 36 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

(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 implement the display node values in a level order traversal (Traverse the tree one level at a time,
starting at the root node) for a binary tree using java program.

DESCRIPTION:

Traversal is a common operation performed on data structures. It is the process in which each and every
element present in a data structure is "visited" (or accessed) at least once. This may be done to display
all of the elements or to perform an operation on all of the elements.

SOURCE CODE:
class Node

int data;

Node left, right;

public Node(int item){

data = item;

left = right = null;

}}

public class BinaryTree{

Node root;

public BinaryTree() {

root = null;

void printLevelOrder() {

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

20JG1A0431 Page 37 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
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;

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:

20JG1A0431 Page 38 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

10. Write a Java program that uses recursive functions. (a) To create a binary search tree.
(b) To count the number of leaf nodes. (c) To copy the above binary search tree.
AIM: To implement the uses recursive functions. (a) To create a binary search tree. (b) To count the number of leaf
nodes. (c) To copy the above binary search tree using a java program.

DESCRIPTION:

Recursive Function is a function that repeats or uses its own previous term to calculate subsequent terms
and thus forms a sequence of terms. Usually, we learn about this function based on the
arithmetic-geometric sequence, which has terms with a common difference between them.

SOURCE CODE:
class Node {

int item;

Node left, right;

public Node(int key)

item = key; left = right = null;

}}

class Mains {

Node root;

Mains() {

root = null;

public static int countLeaf(Node node){

if(node == null){

return 0;

if (node.left == null && node.right == null) {

return 1;

else{

return countLeaf(node.left) + countLeaf(node.right);

} }

public static void main(String[] args)

20JG1A0431 Page 39 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
{

Mains tree = new Mains();

tree.root = new Node(5);

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

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

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

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

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

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

int leafNodes = countLeaf(tree.root);

System.out.println("Total Leaf Nodes = " + leafNodes);

}}

OUTPUT:

20JG1A0431 Page 40 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

11. Write Java programs for the implementation of bfs and dfs for a given graph.
AIM: To implement the java program of bfs and dfs for a given graph.

DESCRIPTION:

BFS can be used to find a single source shortest path in an unweighted graph because, in BFS, we reach a
vertex with a minimum number of edges from a source vertex. In DFS, we might traverse through more
edges to reach a destination vertex from a source.

11b)write a java program for the implementation of DPS for a given graph

SOURCE CODE:

import java.io.*;

import java.util.*;

class Graph {

private int V;

private LinkedList<Integer> adj[];

public Graph(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 DFSUtil(int vertex, boolean nodes[]) {

nodes[vertex] = true;

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

int a = 0;

for (int i = 0; i < adj[vertex].size(); i++) {

a = adj[vertex].get(i);

if (!nodes[a]) {

DFSUtil(a, nodes);

20JG1A0431 Page 41 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
} } }

void DFS(int v){

boolean already[] = new boolean[V];

DFSUtil(v, already);

public static void main(String args[]){

Graph g = new Graph(6);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 0);

g.addEdge(1, 3);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 4);

g.addEdge(3, 5);

g.addEdge(4, 3);

g.addEdge(5, 3);

System.out.println("Following is Depth First Traversal: ");

g.DFS(0);

}}

OUTPUT:

11.B write java program for the implementation of BFS for a given graph

import java.io.*;

import java.util.*;

20JG1A0431 Page 42 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
class Graph1

private int V;

private LinkedList<Integer> adj[];

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];

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

}}}}

20JG1A0431 Page 43 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
public static void main(String args[]){

Graph1 g = new Graph1(4);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(1, 2);

g.addEdge(2, 0);

g.addEdge(2, 3);

g.addEdge(3, 3);

System.out.println("Following is Breadth First Traversal "+

"(starting from vertex 2)");

g.BFS(2);

}}

OUTPUT:

20JG1A0431 Page 44 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

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

c) Insertion sort d) Radix sort

DESCRIPTION:

Bubble sort is a basic algorithm for arranging a string of numbers or other elements in the correct order.
The method works by examining each set of adjacent elements in the string, from left to right, switching
their positions if they are out of order.
Selection sort is an effective and efficient sort algorithm based on comparison operations. It adds one
element in each iteration. You need to select the smallest element in the array and move it to the beginning
of the array by swapping with the front element.
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a
time by comparisons. It is much less efficient on large lists than more advanced algorithms such as
quicksort, heapsort, or merge sort.
Radix sort is an integer sorting algorithm that sorts data with integer keys by grouping the keys by
individual digits that share the same significant position and value (place value). Radix sort uses
counting sort as a subroutine to sort an array of numbers.

(a)Bubble sort:

SOURCE CODE:

public class BubbleSortExample

static void bubbleSort(int[] arr) {

int n = arr.length;

int temp = 0;

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

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

if(arr[j-1] > arr[j]){

//swap elements

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

} } } }

20JG1A0431 Page 45 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
public static void main(String[] args) {

int arr[] ={3,60,35,2,45,320,5};

System.out.println("Array Before Bubble Sort");

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

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

System.out.println();

bubbleSort(arr);//sorting array elements using bubble sort

System.out.println("Array After Bubble Sort");

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

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

}}}

OUTPUT:

(a) Selection sort:

SOURCE CODE:

public class SelectionSortExample

public static void selectionSort(int[] arr) {

for (int i = 0; i < arr.length - 1; i++) {

int index = i;

for (int j = i + 1; j < arr.length; j++) {

if (arr[j] < arr[index]){

index = j;//searching for lowest index

20JG1A0431 Page 46 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
} }

int smallerNumber = arr[index];

arr[index] = arr[i];

arr[i] = smallerNumber;

}}

public static void main(String a[]){

int[] arr1 = {9,14,3,2,43,11,58,22};

System.out.println("Before Selection Sort");

for(int i:arr1){

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

System.out.println();

selectionSort(arr1);//sorting array using selection sort

System.out.println("After Selection Sort");

for(int i:arr1){

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

} }}

OUTPUT:

(C) InsertionSort():

SOURCE CODE:

public class InsertionSortExample

public static void insertionSort(int array[]) {

int n = array.length;

20JG1A0431 Page 47 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
for (int j = 1; j < n; j++) {

int key = array[j];

int i = j-1;

while ( (i > -1) && ( array [i] > key ) ) {

array [i+1] = array [i];

i--;

array[i+1] = key;

}}

public static void main(String a[]){

int[] arr1 = {9,14,3,2,43,11,58,22};

System.out.println("Before Insertion Sort");

for(int i:arr1){

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

System.out.println();

insertionSort(arr1);//sorting array using insertion sort

System.out.println("After Insertion Sort");

for(int i:arr1){

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

} } }

OUTPUT:

d:Insertion Sort():

SOURCE CODE:

20JG1A0431 Page 48 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
class RadixSort

int getMax(int a[], int n){

int max = a[0];

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

if(a[i] > max)

max = a[i];

return max; //maximum element from the array

void countingSort(int a[], int n, int place) {

int[] output = new int[n+1];

int[] count = new int[10];

// Calculate count of elements

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

count[(a[i] / place) % 10]++;

// Calculate cumulative frequency

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

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

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

output[count[(a[i] / place) % 10] - 1] = a[i];

count[(a[i] / place) % 10]--;

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

a[i] = output[i];

void radixsort(int a[], int n) {

int max = getMax(a, n);

for (int place = 1; max / place > 0; place *= 10)

countingSort(a, n, place);

20JG1A0431 Page 49 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
}

void printArray(int a[], int n) {

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

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

public static void main(String args[]) {

int a[] = {151, 259, 360, 91, 115, 706, 34, 858, 2};

int n = a.length;

RadixSort r1 = new RadixSort();

System.out.print("Before sorting array elements are - \n");

r1.printArray(a,n);

r1.radixsort(a, n);

System.out.print("\n\nAfter applying Radix sort, the array elements are - \n");

r1.printArray(a, n);

} }

OUTPUT:

20JG1A0431 Page 50 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023

13. Write a Java program for implementing KMP pattern matching algorithm.
AIM: To implement KMP pattern matching algorithm using java program.

DESCRIPTION:

KMP algorithm is used to find a "Pattern" in a "Text". This algorithm compares character by character from
left to right. But whenever a mismatch occurs, it uses a preprocessed table called "Prefix Table" to skip
characters comparison while matching

SOURCE CODE:

class KMP{

public static void KMP(String text, String pattern)

if (pattern == null || pattern.length() == 0){

System.out.println("The pattern occurs with shift 0");

return;

if (text == null

|| pattern.length() > text.length()){

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

return;

char[] chars = pattern.toCharArray();

int[] next = new int[pattern.length() + 1];

for (int i = 1; i < pattern.length(); i++) {

int j = next[i + 1];

while (j > 0 && chars[j] != chars[i])

{ j = next[j];

if (j > 0 || chars[j] == chars[i]) { next[i + 1] = j + 1;

} }

for (int i = 0, j = 0; i < text.length(); i++) {

if (j < pattern.length() && text.charAt(i) == pattern.charAt(j)) {

20JG1A0431 Page 51 GVPCEW


DATA STRUCTURE USING JAVA 3ECE-1 R20 YEAR 2022-2023
if (++j == pattern.length()){

System.out.println("The pattern occurs with shift " + (i - j + 1));

}}

else if (j > 0) { j = next[j]; i--;

}}}

public static void main(String[] args) { String text = "ABCABAABCABAC";

String pattern = "CAB"; KMP(text, pattern);

}}

OUTPUT:

20JG1A0431 Page 52 GVPCEW

You might also like