Data Structures Using Java Lab - SEZ31
Data Structures Using Java Lab - SEZ31
AIM:
ALGORITHM:
SOURCE CODE:
import java.util.Arrays;
import java.util.Scanner;
public MyArrayList() {
capacity = 10;
size = 0;
elements = new Object[capacity];
}
if (size == capacity) {
expandCapacity();
}
elements[index] = element;
size++;
}
size--;
}
switch (choice) {
case 1:
System.out.print("Enter the element to add: ");
int element1 = sc.nextInt();
list.add(element1);
break;
case 2:
System.out.print("Enter the index to add the element: ");
int index2 = sc.nextInt();
System.out.print("Enter the element to add: ");
int element2 = sc.nextInt();
list.add(index2, element2);
break;
case 3:
System.out.print("Enter the index to remove the element: ");
int index3 = sc.nextInt();
list.remove(index3);
break;
case 4:
System.out.print("Enter the element to remove: ");
int element4 = sc.nextInt();
list.remove(element4);
break;
case 5:
System.out.print("Enter the index to get the element: ");
int index5 = sc.nextInt();
Integer element5 = list.get(index5);
System.out.println("Element at index " + index5 + ": " + element5);
break;
case 6:
System.out.print("Enter the index to set the element: ");
int index6 = sc.nextInt();
System.out.print("Enter the new element: ");
int element6 = sc.nextInt();
list.set(index6, element6);
break;
case 7:
System.out.print("Enter the element to check if it exists: ");
int element7 = sc.nextInt();
boolean exists7 = list.contains(element7);
System.out.println("Element exists: " + exists7);
break;
case 8:
int size8 = list.size();
System.out.println("Size of list: " + size8);
break;
case 0:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice! Try again.");
break;
}
System.out.println();
} while (choice != 0);
sc.close();
}
}
OUTPUT
RESULT:
AIM:
To write a Java programs to implement the List ADT using linked list.
ALGORITHM:
SOURCE CODE:
import java.util.Scanner;
class Node {
int data;
Node next;
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
if (currNode == null) {
System.out.println("Invalid location");
return;
}
newNode.next = currNode.next;
currNode.next = newNode;
}
}
head = head.next;
}
if (head.next == null) {
head = null;
return;
}
if (location == 1) {
head = head.next;
return;
}
currNode.next = currNode.next.next;
}
while (true) {
System.out.println("\nMenu:");
System.out.println("1. Insert");
System.out.println("2. Insert at First");
System.out.println("3. Insert at End");
System.out.println("4. Insert at Specific Location");
System.out.println("5. Delete at First");
System.out.println("6. Delete at End");
System.out.println("7. Delete at Specific Location");
System.out.println("8. Display");
System.out.println("9. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the element to be inserted: ");
int insertElement = scanner.nextInt();
list.insert(insertElement);
break;
case 2:
System.out.print("Enter the element to be inserted at first: ");
int insertElementAtFirst = scanner.nextInt();
list.insertAtFirst(insertElementAtFirst);
break;
case 3:
System.out.print("Enter the element to be inserted at end: ");
int insertElementAtEnd = scanner.nextInt();
list.insertAtEnd(insertElementAtEnd);
break;
case 4:
System.out.print("Enter the element to be inserted: ");
int insertElementAtLocation = scanner.nextInt();
System.out.print("Enter the location: ");
int location = scanner.nextInt();
list.insertAtLocation(insertElementAtLocation, location);
break;
case 5:
list.deleteAtFirst();
break;
case 6:
list.deleteAtEnd();
break;
case 7:
System.out.print("Enter the location: ");
int deleteLocation = scanner.nextInt();
list.deleteAtLocation(deleteLocation);
break;
case 8:
list.display();
break;
case 9:
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice");
break;
}
}
}
}
OUTPUT
RESULT:
AIM:
To write a Java program to implement the Stack operations using Singly Linked Lists.
ALGORITHM:
OUTPUT:
E:\csjava2a>javac StackDemo.java
E:\csjava2a>java StackDemo
IMPLEMENTATION OF STACK USING LINKED LIST
1. Push 2. Pop 3. View 4. Peek 5.Exit
enter your choice:
1
Enter Data :
10
enter your choice:
1
Enter Data :
20
enter your choice:
1
Enter Data :
30
enter your choice:
3
Elements of the stack are:
30
20
10
enter your choice:
2
popped element = 30
enter your choice:
4
top of the stack=20
RESULT:
Thus, the Java program to implement the Stack operations using Singly Linked List has been
executed successfully.
2.2. IMPLEMENTATION OF QUEUE ADT USING SINGLY LINKED LIST
AIM:
To write a Java program to implement the Queue operations using Singly Linked Lists.
ALGORITHM:
OUTPUT:
E:\csjava2a>javac QueueDemo.java
E:\csjava2a>java QueueDemo
IMPLEMENTATION OF QUEUE USING LINKED LIST
1. enqueue 2. dequeue 3. view 4. Front 5. Rear 6. Exit
enter your choice:
1
Enter Data :
10
enter your choice:
1
Enter Data :
20
enter your choice:
1
Enter Data :
30
enter your choice:
3
Elements of the Queue are:
10
20
30
enter your choice:
4
front =10
enter your choice:
5
rear =30
enter your choice:
2
popped element = 10
enter your choice:
3
Elements of the Queue are:
20
30
RESULT:
Thus, the Java program to implement the Queue operations using Linked List has been
executed successfully.
3.1. CONVERSION OF INFIX EXPRESSION INTO POSTFIX EXPRESSION
AIM:
To write a Java program to convert the given Infix expression to Postfix form using Stack.
ALGORITHM:
Step 1 : Start the execution.
Step 2 : Scan the infix notation from left to right one character at a time.
Step 3 : If the next symbol scanned as an operand, append it to the postfix string.
Step 6 : If a right parenthesis is scanned, all operators down to the most recently
scanned left parenthesis must be popped and appended to the postfix string. Furthermore, the pair
of parentheses must be discarded.
Step 7 : When the infix string is fully scanned, the stack may still contain some operators.
All the remaining operators should be popped and appended to the postfix string.
SOURCE CODE:
import java.util.*;
import java.util.Stack;
class Expression
{
static int prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
static String conversion(String exp)
{
String result = new String("");
Stack <Character> st = new Stack<>();
for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
st.push(c);
else if (c == ')')
{
while (!st.isEmpty() &&
st.peek() != '(')
result += st.pop();
st.pop();
}
else
{
while (!st.isEmpty() && prec(c) <= prec(st.peek()))
{
result += st.pop();
}
st.push(c);
}
}
while (!st.isEmpty())
{
if(st.peek() == '(')
return "Invalid Expression";
result += st.pop();
}
return result;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Infix to Postfix Expression Conversion");
System.out.println("Enter a Expression:");
String exp = s.next();
System.out.println("Postfix Expression:"+conversion(exp));
}
}
OUTPUT:
E:\csjava2a>javac Expression.java
E:\csjava2a>java Expression
Infix to Postfix Expression Conversion
Enter a Expression:
a*(b+c)/d
Postfix Expression:abc+*d/
RESULT:
Thus, the Java program to convert the given Infix Expression to postfix form using Stack has been executed
successfully.
3.2. EVALUATION OF POSTFIX EXPRESSION USING STACK ADT
AIM:
To write a Java program to evaluate the given Postfix Expression using Stack.
ALGORITHM:
SOURCE CODE
import java.util.*;
import java.util.Stack;
class Postfix
{
static int evaluatePostfix(String exp)
{
Stack<Integer> stack=new Stack<>();
for(int i=0;i<exp.length();i++)
{
char c=exp.charAt(i);
if(Character.isDigit(c))
stack.push(c - '0');
else
{
int val1 = stack.pop();
int val2 = stack.pop();
switch(c)
{
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2- val1);
break;
case '/':
stack.push(val2/val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Expression Evaluation");
System.out.println("Enter a Expression:");
String exp = s.next();
System.out.println("postfix evaluation: "+evaluatePostfix(exp));
}}
OUTPUT:
E:\csjava2a>javac Postfix.java
E:\csjava2a>java Postfix
Expression Evaluation
Enter a Expression:
431*+5-
postfix evaluation: 2
RESULT:
Thus, the Java program to evaluate the Postfix expression using stack has been executed
successfully.
4. IMPLEMENTAION OF PRIORITY QUEUE ADT
AIM:
To write a java program to implement priority queue ADT.
ALGORITHM:
Step 1: Start the execution.
Step 2: The insert() method is used to add the element at the rear of the queue.
Step 3: The delete() method is used to remove the element at the front of the queue.
Step 4: The peek() method is used to return the first element at the front of the queue.
Step 5: The display() method is used to display all the elements of the queue.
Step 6: Stop the execution.
SOURCE CODE:
class Node
{
String data;
int prn;
Node next;
Node( String str, int p )
{
data = str; prn = p;
}
}
class LinkedPriorityQueue
{
Node head;
public void insert(String item, int pkey)
{
Node newNode = new Node(item, pkey);
int k;
if( head == null ) k =1;
else if( newNode.prn<head.prn) k =2;
else
k = 3;
switch( k )
{
case 1: head = newNode;
head.next = null; break;
case 2: Node oldHead = head;
head = newNode; newNode.next = oldHead; break;
case 3: Node p = head;
Node prev = p;
Node nodeBefore = null;
while( p != null )
{
if( newNode.prn<p.prn )
{
nodeBefore = p; break;
}
else
{
prev = p; p = p.next;
}
}
newNode.next = nodeBefore; prev.next = newNode;
}
}
public Node delete()
{
if( isEmpty() )
{
System.out.println("Queue is empty"); return null;
}
else
{
Node tmp = head; head = head.next; return tmp;
}
}
public void displayList()
{
Node p = head;
System.out.print("\nQueue: ");
while( p != null )
{
System.out.print(p.data+"(" +p.prn+ ")" + " ");
p = p.next;
}
System.out.println();
}
public boolean isEmpty()
{
return (head == null);
}
public Node peek()
{
return head;
}
}
class LinkedPriorityQueueDemo
{
public static void main(String[] args)
{
LinkedPriorityQueue pq = new LinkedPriorityQueue();
Node item;
pq.insert("Balu", 3);pq.insert("Vino",2);pq.insert("Ram",2);pq.insert("Sree", 1);
pq.insert("Suresh", 3); pq.displayList();item = pq.delete();
if( item != null )
System.out.println("delete():" + item.data + "(" +item.prn+")");pq.displayList();
pq.insert("Tino", 2);pq.insert("Lucky", 1); pq.insert("Mickey", 4); pq.displayList();
}
}
OUTPUT
RESULT:
Thus, the Java program to implement priority queue has been executed successfully.
5. (a) INSERTING AN ELEMENT INTO A BINARY SEARCH TREE
Aim:
To write a Java Program to insert an element into the Binary Search Tree.
Algorithm:
Step 1 : Start the execution
Step 2 : Read the value of n.
Step 3 : Using for loop, read the node elements one by one.
Step 4 : Start from the root.
Step 3 : Compare the element to be inserted with the root node.
Step 4 : If the value of the new node is less than the root node then, it will be inserted to the
left subtree.
Step 5 : If the value of the new node is greater than root node then, it will be inserted to the
right subtree.
Step 6 : On reaching the end node, insert the value left (if the value is smaller than current node
value), else right.
Step 7 : Stop the execution.
SOURCE CODE
class InsertBST {
// Class containing left and right child of current node and key value
class Node
{
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
InsertBST()
{
root = null;
}
// This method mainly calls insertRec()
void insert(int key)
{
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
Node insertRec(Node root, int key)
{
/* If the tree is empty,
return a new node */
if (root == null)
{
root = new Node(key);
return root;
}
/* Otherwise, recur down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the (unchanged) node pointer */
return root;
}
// This method mainly calls InorderRec()
void inorder()
{
inorderRec(root);
}
// A utility function to
// do inorder traversal of BST
void inorderRec(Node root)
{
if (root != null) {
inorderRec(root.left);
System.out.println(root.key);
inorderRec(root.right);
}
}
public static void main(String[] args)
{
InsertBST tree = new InsertBST();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
// print inorder traversal of the BST
tree.inorder();
}
}
OUTPUT:
E:\csjava2a>javac InsertBST.java
E:\csjava2a>java InsertBST
20
30
40
50
60
70
80
5. (b) DELETING AN ELEMENT INTO A BINARY SEARCH TREE
Aim:
To write a Java program to delete an element from a Binary Search Tree.
Algorithm:
Step 1 : Start the execution
Step 2 : Read the value of n.
Step 3 : Using for loop, read the node elements one by one.
Step 2 : Start from the root.
Step 3 : Compare the element to be inserted with the root node.
Step 4 : If the value of the new node is less than the root node then, it will be inserted to the left
subtree.
Step 5 : If the value of the new node is greater than root node then, it will be inserted to the
right subtree.
Step 6 : On reaching the end node, insert the value left (if the value is smaller than current
node value), else right.
Step 7 : Read the value of the node to be deleted.
Step 8 : When we delete a node, three possibilities arise.
i) Node to be deleted is the leaf: Simply remove from the tree.
ii) Node to be deleted has only one child: Copy the child to the node
and delete the child
iii) Node to be deleted has two children: Find inorder successor of the
node. Copy contents of the inorder successor to the node and delete the inorder successor.
Note that inorder predecessor can also be used.
Step 9 : Stop the execution.
SOURCE CODE
class DelBST
{
// A binary tree node
static class Node
{
int data;
Node left, right;
}
// A utility function to allocate a new node
static Node newNode(int data)
{
Node newNode = new Node();
newNode.data = data;
newNode.left = null;
newNode.right = null;
return (newNode);
}
static Node deleteLeaves(Node root, int x)
{
if (root == null)
{
return null;
}
root.left = deleteLeaves(root.left, x);
root.right = deleteLeaves(root.right, x);
if (root.data == x && root.left == null && root.right == null)
{
return null;
}
return root;
}
static void inorder(Node root)
{
if (root == null)
{
return;
}
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void main(String[] args)
{
Node root = newNode(6);
root.left = newNode(5);
root.right = newNode(4);
root.left.left = newNode(1);
root.left.right = newNode(2);
root.right.right = newNode(5);
deleteLeaves(root, 5);
System.out.print("Inorder traversal after deletion : ");
inorder(root);
}
}
OUTPUT:
E:\csjava2a>javac DelBST.java
E:\csjava2a>java DelBST
Inorder traversal after deletion : 1 5 2 6 4
E:\csjava2a>
5.(c) SEARCHING FOR A KEY ELEMENT IN A BINARY SEARCH TREE
Aim:
Algorithm:
SOURCE CODE
class SearchBST
{
static class Node
{
int data;
Node left, right;
Node(int data)
{
this.data = data;
left = right = null;
}
}
// Function to traverse the tree in preorder
// and check if the given node exists in it
static boolean ifNodeExists( Node node, int key)
{
if (node == null)
return false;
if (node.data == key)
return true;
// then recur on left subtree /
boolean res1 = ifNodeExists(node.left, key);
// node found, no need to look further
if(res1) return true;
// node is not found in left,
// so recur on right subtree /
boolean res2 = ifNodeExists(node.right, key);
return res2;
}
public static void main(String args[])
{
Node root = new Node(0);
root.left = new Node(1);
root.left.left = new Node(3);
root.left.left.left = new Node(7);
root.left.right = new Node(4);
root.left.right.left = new Node(8);
root.left.right.right = new Node(9);
root.right = new Node(2);
root.right.left = new Node(5);
root.right.right = new Node(6);
int key = 4;
if (ifNodeExists(root, key))
System.out.println("key is found");
else
System.out.println(key +"key is not found");
}
}
OUTPUT:
E:\csjava2a>javac SearchBST.java
E:\csjava2a>java SearchBST
key is found
6.(a) INSERTION INTO AN AVL TREE
AIM:
ALGORITHM:
SOURCE CODE:
class Node {
int data, height;
Node left, right;
Node(int item) {
data = item;
height = 1;
left = right = null;
}
}
// Class representing the AVL tree
class AVLTree {
Node root;
int height(Node node) {
if (node == null)
return 0;
return node.height;
}
int getBalance(Node node) {
if (node == null)
return 0;
return height(node.left) - height(node.right);
}
Node rotateRight(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;
return x;
}
Node rotateLeft(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;
return y;
}
Node insertNode(Node node, int data) {
if (node == null)
return new Node(data);
if (data < node.data)
node.left = insertNode(node.left, data);
else if (data > node.data)
node.right = insertNode(node.right, data);
else
return node;
node.height = 1 + Math.max(height(node.left), height(node.right));
AIM:
ALGORITHM:
SOURCE CODE:
class Node {
int key, height;
Node leftChild, rightChild;
Node(int value) {
key = value;
height = 1;
}
}
class AVLTree {
Node root;
Node rightRotate(Node y) {
Node x = y.leftChild;
Node T2 = x.rightChild;
x.rightChild = y;
y.leftChild = T2;
Node leftRotate(Node x) {
Node y = x.rightChild;
Node T2 = y.leftChild;
y.leftChild = x;
x.rightChild = T2;
return y;
}
if (temp == null) {
temp = root;
root = null;
} else
root = temp;
} else {
Node temp = minValueNode(root.rightChild);
root.key = temp.key;
root.rightChild = deleteNode(root.rightChild, temp.key);
}
}
if (root == null)
return root;
if (balanceFactor > 1) {
if (getBalanceFactor(root.leftChild) >= 0)
return rightRotate(root);
else {
root.leftChild = leftRotate(root.leftChild);
return rightRotate(root);
}
}
return root;
}
Aim:
To write a Java program to implement the BFS for a given graph.
Algorithm:
Step 1 : Start the execution.
Step 2 : Create an empty queue and push root node to it.
Step 3 : Do the following when the queue is not empty.
Step 4 : Pop a node from queue and print it.
Step 5 : Find neighbors of node with the help of adjacency matrix and check if node is
already visited or not.
Step 6 : Push neighbors of node into queue if not null
Step 7 : Stop the execution.
Program:
//Java Program to implement Breadth First Search on a graph non-recursively
//BreadthFirstSearch.java
import java.io.*;
import java.util.*;
public class BreadthFirstSearch
{
// Function to perform breadth first search
static void breadthFirstSearch(int[][] matrix, int source)
{
boolean[] visited = new boolean[matrix.length];
visited[source-1] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
System.out.println("The breadth first order is");
while(!queue.isEmpty())
{
System.out.println(queue.peek());
int x = queue.poll();
int i;
for(i=0; i<matrix.length;i++)
{
if(matrix[x-1][i] == 1 && visited[i] == false)
{
queue.add(i+1);
visited[i] = true;
}
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vertices;
System.out.println("Enter the number of vertices in the graph");
vertices = Integer.parseInt(br.readLine());
int[][] matrix = new int[vertices][vertices];
System.out.println("Enter the adjacency matrix");
for(int i=0; i<vertices; i++)
{
for(int j=0; j<vertices; j++)
{
matrix[i][j] = Integer.parseInt(br.readLine());
}
}
int source;
System.out.println("Enter the source vertex");
source = Integer.parseInt(br.readLine());
breadthFirstSearch(matrix,source);
}
}
Output:
Enter the number of vertices in the graph
3
Enter the adjacency matrix
0
0
0
1
0
1
1
1
1
Enter the source vertex
2
The breadth first order is
2
1
3
Result:
Thus, the Java program to implement the Breadth First Search for a graph has been executed
successfully.
8. IMPLEMENTATION OF DFS FOR A GIVEN GRAPH
Aim:
To write a Java program to implement the DFS for a given graph.
Algorithm:
Step 1: Start the execution.
Step 2: Create a stack of nodes and visited array.
Step 3: Insert the root in the stack.
Step 4: Run a loop till the stack is not empty.
Step 5: Pop the element from the stack and print the element.
Step 6: For every adjacent and unvisited node of current node, mark the node and insert it
in the stack.
Step 7: Stop the execution.
Program:
//Java Program to implement the Depth First Search for a Graph
//DepthFirstSearch.java
import java.io.*;
import java.util.*;
public class DepthFirstSearch
{
static void depthFirstSearch(int[][] matrix, int source)
{
boolean[] visited = new boolean[matrix.length];
visited[source-1] = true;
Stack<Integer> stack = new Stack<>();
stack.push(source);
int i,x;
System.out.println("The depth first order is");
System.out.println(source);
while(!stack.isEmpty())
{
x = stack.pop();
for(i=0; i<matrix.length; i++)
{
if(matrix[x-1][i] == 1 && visited[i] == false)
{
stack.push(x);
visited[i] = true;
System.out.println(i+1);
x = i+1;
i = -1;
}
}
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vertices;
System.out.println("Enter the number of vertices in the graph");
vertices = Integer.parseInt(br.readLine());
int[][] matrix = new int[vertices][vertices];
System.out.println("Enter the adjacency matrix");
for(int i=0; i<vertices; i++)
{
for(int j=0; j<vertices; j++)
{
matrix[i][j] = Integer.parseInt(br.readLine());
}
}
int source;
System.out.println("Enter the source vertex");
source = Integer.parseInt(br.readLine());
depthFirstSearch(matrix,source);
}
}
Output:
Enter the number of vertices in the graph
3
Enter the adjacency matrix
0
0
0
1
0
1
1
1
1
Enter the source vertex
3
The depth first order is
3
1
2
Result:
Thus, the Java program to implement the Depth First Search for a graph has been executed
successfully.
9. (a) LINEAR SEARCH
AIM:
ALGORITHM:
SOURCE CODE:
import java.util.Scanner;
class LinearSearchExample
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter those " + n + " elements");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}
OUTPUT
9. (b) BINARY SEARCH
AIM:
ALGORITHM:
SOURCE CODE:
class BinarySearchExample
{
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{
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:
10. (a) BUBBLE SORT
AIM:
ALGORITHM:
SOURCE CODE:
AIM:
ALGORITHM:
SOURCE CODE:
AIM:
ALGORITHM:
SOURCE CODE:
AIM:
ALGORITHM:
SOURCE CODE:
import java.util.Scanner;
public class RadixSort{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
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++) // Initialize the buckets
{
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;
}
}
}
OUTPUT