Dsa Record-2022 - Batch - CS
Dsa Record-2022 - Batch - CS
Name :
Register Number :
Class :
Subject :
RVS COLLEGE OF ARTS AND SCIENCE
REGISTER NUMBER
..........................................................................................................practical work
doneby
Mr./Ms pursuing
Faculty HoD
Internal…………………………..….
External………………….……….…
o
EX. NO: 1 FACTORIAL OF N NUMBERS USING RECURSION DATE :
Aim:
To Develop a Java function to perform a Factorial of N numbers using Recursion and
specify its Time Complexity.
● Using the “scanner class” object “in” get the input for finding the Factorial.
● Assign the input received from the input source to an integer variable “n”.
● Check whether the input is a positive integer
● If the value of “n<0”, print as “Invalid number”.
● Else invoke “Factorial Function”
ALGORITHM:
1
STEP 5: Display the factorial of a given number as output.
CODE:
2
EXECUTION 2:
EXECUTION 3:
TIME COMPLEXITY
The Time Complexity for finding the factorial of a given number using recursion is O(N)
3
RESULT:
Thus, the program for finding the factorial using recursion has been executed and verified
successfully.
4
5
EX. NO: 2 REVERSING A STRING USING RECURSION DATE :
Aim:
To write a Java function to reverse a string using Recursion and specify its Time
Complexity.
TASK 1:Creating the Class“stringReverse”
● Using the “scanner class” object “input”gets the input for reversing the String.
● Assign the input received from the input source to astring variable “str”.
● Print the Reversed String by passing the parameter str, empty string (“ ”) as
reversed, “0” as starting index, and “str.length()-1” as end index.
ALGORITHM:
STEP 1: Include the parameter “str”, “reversed”, “startIndex”, and ” endIndex” to reverse the
String.
STEP 2:Check Base Case: Use “If Statement” to Check whether the “startIndex” is greater
than the “endIndex”, terminate and return the empty string as output.
STEP 3:Check for Recursive Case: Recursively invoke reverseString function and append
the “endIndex” character with the“reversed”
STEP 4: Return the reverseString function by passing the parameter “str”, ”reversed”,”
startIndex”,” endIndex-1”
1
import java.util.Scanner;
args)
String reversed="";
public static String reverseString(String str, String reversed, int startIndex, int
}
OUTPUT:
EXECUTION 1
2
TIME COMPLEXITY
The Time Complexity to reverse a string using Recursion is O(N)
3
RESULT:
Thus, the program for reversing a string has been executed and verified successfully
4
EX. NO:3 FIND THE SECOND-HIGHEST NUMBER IN AN ARRAY DATE :
Aim:
To write a Java function to find the second-highest number in an array and specify its Time
Complexity.
● Using the “scanner class” object “sc”gets the input size for finding the second
highest number.
● Assign the input sizereceived from the input source to aninteger variable “n”.
● Do Inline Initialization for array variable “arr” of “n” Size.
● Use the “for loop” to get the n inputs from the user, limits to the size “n”.
● Within the “for loop” Use the “scanner class” object “sc.nextInt” to get the input
and assign it to variable “arr[i]”.
● Assign the findSecondLargest(arr) function to the integer
variable
“secondLargest:
● Print the Second Largest number by passing the array “arr” as the parameter.
ALGORITHM:
TIME COMPLEXITY:
The Time Complexity to find the second highest number in an array is O(N)
Aim:
To write a Java function to perform array insertion at a given position and specify its
Time Complexity.
TASK 1: Creating the Class“Array_Insertion”
● Import the util package
● Create a class named” Array_Insertion”.
TASK 2: Creating the Main Function
● Declare the following integer variables o Variable” len” for storing the length of
the array o Variable “p” for getting position to insert the new element in the array.
o Variable “e” for getting the element to be inserted inthe given position.
● Using the “scanner class” object “sc” get the length of the array and elements of
the array.
● Increase the length of the array to add the new element by using “len+1” and assign
it to the integer array variable “ arr[]”.
● Use the “for loop” to get the elements of the array limiting to the length “len”.
● Within the “for loop” Use the “scanner class” object “sc.nextInt” to get the input
and assign it to variable “arr[i]”.
● Get the position of the element to be inserted in the array using the variable “p”.
● Get the element to be inserted in the array using the variable “e”.
● Call the arrayInsert() by passing the parameter “arr,p,e,len”.
ALGORITHM:
import java.util.Scanner;
{
System.out.println("arr["+i+"]="+arr[i]);
}
}
}
OUTPUT:
EXECUTION 1:
TIME COMPLEXITY:
The Time Complexity to find the second highest number in an array is O(N)
Thus, the program for finding the second-highest number in an array has been executed and
verified successfully.
EX. NO: 5 LENGTH OF THE LINKEDLIST
DATE :
Aim:
To write a Java function to find the length of the singly linked list and specify its Time
Complexity.
● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method
ALGORITHM:
Implement the Length Function.
STEP 1: Initialize Variable “count to 0”and set“current” to the head of the linked list.
STEP 2: Traverse the Linked List Using a “while loop” to travel as long as the current is
not null.
● Inside the loop Increment count by 1.
● Move current to the next node in the linked list.
STEP 3: Return thefinal value of count as the length of the linked list.
CODE:
import java.util.Scanner;
public class LinkedList {
class Node
{ int data;
Node next; public
Node(int data)
{ this.data = data;
this.next = null;
}
}
The Time Complexity to find the length of the Linked List is O(N)
Aim:
To write a Java function to perform the insert at middle operation in the singly linked list
and specify its Time Complexity.
.
TASK 1: Creating the Class “linkedList”
● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs.
● Inside the loop o Read the next integer using the Scanner method.
● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method
variable “data”.
ALGORITHM:
Implement the Insert at middle Function.
STEP 1: Include the parameters “data” and “pos”with the Integer data type.
STEP 2: Create a new node with a variable “newNode” with the given data.
STEP 3: Initialize a temporary node with the variable “temp” pointing to the head of the
linked list.
STEP 4: Check whether the specified position “pos = 1” using “IF Statement”:
STEP 4.1: If true, set “newNode.next” to the current head, and update the head to the new
node.
STEP 5: If the position is not 1, iterate through the linked list until reaching the node just
before the desired position:
STEP 5.1:Use a “For loop” to traverse the list for "pos-1” times.
STEP 5.2:Update the variable “temp” node to point to the desired position.
STEP 6:Insert the new node “newNode” into the linked list:
STEP 6.1:Set variable “newNode.next” to the current node at the desired position.
STEP 6.2:Update the next reference of the “temp” node to point to the new node.
STEP 7:Display a message prompting the “Element Inserted” to indicate the successful
insertion.
CODE:
import java.util.Scanner;
public class LinkedList {
class Node
{ int data;
Node next;
if(sc.hasNextInt())
{
data = sc.nextInt();
list.addNode(data);
}
else
{
String temp=sc.next();
System.out.println("LINKED LIST CREATED");
System.out.println("LINKED LIST BEFORE INSERTING");
list.displayList();
System.out.println("ENTER THE POSITON WHERE YOU WANT TO INSERT");
if(sc.hasNextInt())
{
pos=sc.nextInt();
System.out.println("ENTER THE ELEMENT TO BE INSERTED:");
if(sc.hasNextInt())
{ data1=sc.nextInt();
list.insertMiddle(data1,pos)
;
System.out.println("LINKED LIST AFTER INSERTING");
list.displayList();
}
else
{
System.out.println("Enter integers only");
System.exit(0);
}
}
else
{
System.out.println("Enter integers only");
System.exit(0);
}
}
}
} public void insertMiddle(int data,int
pos)
{
//Create a new node
Node newNode = new Node(data);
//temporary node points to head node
Node temp=head;
if(pos==1)
{
newNode.next=temp;
head=newNode;
} else { for(int i=1;i<(pos-
1);i++ )
{
temp = temp.next;
} newNode.next=temp.next;
temp.next=newNode;
}
System.out.println("Element Inserted");
TIME COMPLEXITY:
The Time Complexity to Insert a node in the middle of the Linked List is O(N)
Aim:
To write a Java function to perform the insertion at the end operation in the singly linked
list and specify its Time Complexity.
TASK 1: Creating the Class “linkedList”
● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o Read the next integer using the Scanner method.
● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method
ALGORITHM:
STEP 2: Create a new node variable “newNode” with the given data.
STEP 3: Check whether the linked list is empty (head is null) using “IF Statement”
STEP 3.1: If true, set both head and tail to the new node.
STEP 4: Initialize a temporary pointer “temp” to the head of the linked list.
STEP 5: Traverse the linked list using a while loop until “temp.next” is null.
STEP 5.1: Within the loop, move” temp” to the next node.
STEP 6: Display a message prompting the “Elements Inserted” to indicate the successful
insertion
CODE:
import java.util.Scanner;
int pos=0;
int data,data1;
System.out.println("ENTER INTEGERS TO CREATE NODES (ENTER A NON-INTEGER
TO EXIT):");
while (sc.hasNext())
{
if(sc.hasNextInt())
{ data =
sc.nextInt();
list.addNode(data);
}
else
{
String temp=sc.next();
System.out.println("LINKED LIST CREATED");
System.out.println("LINKED LIST BEFORE INSERTING");
list.displayList();
System.out.println("ENTER THE ELEMENT TO BE INSERTED:");
if(sc.hasNextInt())
{
data1=sc.nextInt();
list.insertEnd(data1);
}
else{
System.out.println("Enter integers only");
System.exit(0);
}
System.out.println("LINKED LIST AFTER INSERTING");
list.displayList();
}
}
} public void insertEnd(int
data)
{
//Create a new node
Node newNode = new Node(data);
//Checks if the list is empty
if(head == null)
{
//If list is empty, both head and tail will point to new
node head = newNode; tail = newNode;
}
else
{
Node temp=head;
while( temp.next!=
null)
{
temp = temp.next;
}
temp.next=newNode;
System.out.println("Element Inserted");
}
}
TIME COMPLEXITY:
The Time Complexity to Insert a node at the end of the Linked List is O(N)
RESULT:
Thus, the program for inserting a node at the end of the Linked List has been executed and verified
successfully.
EX. NO: 8 DELETING A NODE AT THE END OF THE LINKED LIST DATE :
Aim:
To write a Java function to perform the deletion at tail operation in the singly linked list
and specify its Time Complexity.
TASK 1: Creating the Class “linkedList”
● Import the util package
● Create a class named” linkedList”.
TASK 2: Create a Node class:
● Define a class Node with integer data and a reference to the next node (next).
● Include a constructor to initialize the node with the given data.
TASK 3: Initialize head and tail in LinkedList class:
● In the LinkedList class, initialize both head and tail to null.
TASK 4: Creating addNode() Function
● Create a new node for the data.
● If the linked list is empty (head is null), set both head and tail to the new node.
● If the linked list is not empty, add the new node after the current tail and update the
tail to the new node.
TASK 5: Creating the Main Function
● Using the “scanner class” object “sc” get the elements of the LinkedList.
● Display a message prompting the user to enter integers to create nodes.
● Create a “While loop” that continues as long as the user inputs as integers
● Inside the loop o Read the next integer using the Scanner method.
● Display a message indicating that the linked list has been created.
o Print the contents of the linked list using a displayList method
ALGORITHM:
STEP 1:Check whether the linked list is emptyusingthe “IF Statement”
STEP 1.1If true, display a message prompting the “List is Empty”.
STEP 1.2 If false, proceed to the next step.
STEP 2: Checkwhether there is only one node in the linked listusing “IF Statement”
STEP 2.1: If true, set head to null.
STEP 2.2: If false, proceed to the next step.
STEP 3: Initialize two pointers, “temp” and “prev`”, both pointing to the head of the linked
list.
STEP 4: Traverse the linked list using a while loop until “temp.next.next” is null.
STEP 4.1: Within the loop, update “prev”pointer to point to the next node and update
the“temp” to the “temp.next”
STEP 5: After the loop, move “temp” to the last node.
STEP 6: Set“prev.next” to null, effectively removing the last node from the linked list.
STEP 7: Print the data of the deleted element (last node).
CODE:
import java.util.Scanner;
public class LinkedList {
class Node
{ int data;
Node next;
while (sc.hasNextInt()) {
int data = sc.nextInt();
list.addNode(data);
}
System.out.println("Linked List created");
}
public void displayList() { Node current =
head; while (current != null)
{ System.out.print(current.data + " ->
"); current = current.next;
}
System.out.println("null");
}
}
OUTPUT:
EXECUTION I
TIME COMPLEXITY:
The Time Complexity to Deletea node at the end of the Linked List is O(N)
RESULT:
Thus, the program fordeletinga node at the end of the Linked List has been executed and verified
successfully.
EX. NO: 9 STACK USING ARRAY
DATE :
Aim:
To develop a Java functionto perform push (), Pop(), isEmpty(), and IsFull()
operations in Stack using an array, to check for overflow and Underflow status, and Display
the Elements after each operation. Specify its Time Complexity.
TASK 1: Creating the Class “ArrayStack”
● Import the util package
● Create a class named”ArrayStack”.
TASK 2: Initializations:
● Declare “Capacity” with Integer Datatype.
● Declare “stack” with Integer Array,
● Do Inline Initialization for variable “top=-1” with Integer Type
TASK 3: Create a parameterized Constructor “cap” for “ArrayStack” for accessing Global
Variable “Capacity”
● Assign “Cap” to “Capacity”
TASK 4: Create a Function “Size”
● Return top+1
TASK 5: Creating the Display Function
● Check whether the Stack is Empty by calling “isEmpty()” using the “IF” Statement
and Display a message prompting “Stack is Underflow. No elements to display in
Empty Stack”
● Else Display a message prompting “Stack Elements: Top of the Stack Element is”
● Iterate backward to print the Stack Elements Starting with “top”
TASK 6: Creating the Main Function
● Create a new instance of “ArrayStack” with the Specified Capacity ● Using the
“scanner class” object “sc” to perform Stack Operations.
● Display a menu with the options: Push, Pop, Display, and Exit using Switch
Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice
● Repeat the menu until the user chooses to Exit.
ALGORITHMIII:ISFULL() FUNCTION:
STEP 1:Invoke Size() method to get the current size of the stack(top+1)
STEP 2:Compare the current size of the stack with the capacity(Maximum size of the stack)
STEP 2.1:If the current size is equal to the capacity, the stack is considered full, and the
method returns true
STEP 2.2:otherwise, it returns false
ALGORITHMIV:ISEMPTY() FUNCTION:
STEP 1:Checkwhether the top pointer of the stack is less than 0 using “If” Statement
STEP 1.1:If it is true the stack is considered empty, and the function returns true.
STEP 1.2:Otherwise, it returns false, indicating that the stack is not empty.
CODE:
import java.util.*; public
class ArrayStack{ protected
int capacity; protected int[]
stack; protected int top = -1;
public ArrayStack(int cap)
{ capacity = cap; stack =
new int[capacity];
} public int
size()
{ return (top+1);
}
public void push(int data)
{
if (isFull())
System.out.println("Stack is Overflow. Not possible to insert in Full stack");
else
{
stack[++top] = data;
System.out.println("Element is inserted");
}
}
} return
data; }
public booleanisFull()
{ return
(size()==capacity);
}
public booleanisEmpty()
{ return (top<0);
}
public void display()
{ if(isEmpty())
System.out.println("Stack is Underflow. No elements to display in Empty Stack");
else
{
System.out.println("Stack Elements:Top of the Stack Element is");
for(int i=top;i>=0;i--)
System.out.println(stack[i]);
}
}
public static void main(String[] args)
{
ArrayStack s=new ArrayStack(5);
Scanner sc=new Scanner(System.in);
int data,ch; do
{
System.out.println("\n1.Push");
System.out.println("2.Pop");
System.out.println("3.Display Stack");
System.out.println("4.Exit\n");
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch)
{ case 1:
System.out.println("Enter the element to insert:");
data=sc.nextInt();
s.push(data);
break;
case 2:
data=s.pop();
if(data!=-1)
System.out.println("Popped Element:"+data);
break;
case 3:
s.display();
break;
} }while(ch<4);
}
}
OUTPUT:
EXECUTION
TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Stack Using an Array isO(1)
The Time Complexity for Deleting an Element in a Stack Using an Array isO(1)
The Time Complexity for Stack isFUll() Using an Array is O(1)
The Time Complexity for Stack is isEmpty() Using an Array is O(1)
The Time Complexity for Displaying N Elements is O(N)
RESULT:
Thus, the program for Stack operations using arrayhas been executed and verified successfully.
Aim:
To develop a Java function to perform the push and pop operation in Stack using a linked
list and specify its Time Complexity.
▪ Push the integer onto the stack using the push method.
variable).
▪ Print a message indicating the creation of the stack using a
linked list.
method.
● Display a menu with the options: Push, Pop, Display, and Exit using Switch
Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice ● Repeat the menu until
the user chooses to Exit.
ALGORITHM I: Creating ISEMPTY() :
STEP 1: Check whether the top pointer of the stack is equal to Null using “If” Statement
STEP 1.1: If it is true the stack is considered empty, and the function returns true.
STEP 1.2: Otherwise, it returns false, indicating that the stack is not empty.
{ case 1:
System.out.println("ENTER THE ELEMENT TO PUSH INTO
STACK:"); data=scanner.nextInt(); stack.push(data);
System.out.println("STACK ELEMENTS AFTER PUSH OPERATION
ARE:"); stack.displayStack(); break;
case 2:
data=stack.pop(); if(data!=-
1)
{
System.out.println("POPPED ELEMENT IS:"+data);
System.out.println("STACK ELEMENTS AFTER POP");
stack.displayStack();
}
break;
case 3:
System.exit(0);
}}while(ch<3);
}
}
scanner.close();
}
public void displayStack()
{ Node current = top;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
}
OUTPUT
EXECUTION I
TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Stack Using a Linked List is O(1)
The Time Complexity for Deleting an Element in a Stack Using a Linked List is O(1)
The Time Complexity for Stack is isEmpty() Using a Linked List is O(1)
The Time Complexity for Displaying N Elements is O(N)
RESULT:
Thus, the program for Stack operations using Linked List has been executed and verified
successfully.
}
else { data =
stack[top]; top--;
}
System.out.print(data);
}
public boolean isFull()
{ return (size()==capacity);
}
public boolean isEmpty()
{ return (top<0);
}
}
}
OUTPUT:
EXECUTION I
TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Stack Using an Array is O(1)
The Time Complexity for Deleting an Element in a Stack Using an Array is O(1)
The Time Complexity for Stack isFUll() Using an Array is O(1)
The Time Complexity for Stack is isEmpty() Using an Array is O(1)
The Time Complexity for Reversing a String is O(N)
RESULT:
Thus, the program for String reverse using Stack has been executed and verified successfully.
EX. NO: 12 QUEUE USING ARRAY
DATE :
Aim:
To write a Java function to perform the enqueue and dequeue underflow and overflow
status in the Queue using an array and specify its Time Complexity.
}
else { front++; data
= queue[front];
} return
data; }
public boolean isFull()
{ return
(size()==capacity);
}
public boolean isEmpty()
{ return
(front==rear);
}
public void display()
{ if(isEmpty())
System.out.println("Queue is Underflow. No elements to display in Empty Queue");
else
{
System.out.println("Queue Elements");
for(int i=front+1;i<=rear;i++)
System.out.print(queue[i]+"\t");
}
}
public static void main(String[] args)
{
ArrayQueue q=new ArrayQueue(5);
Scanner sc=new Scanner(System.in);
int data,ch;
do
{
System.out.println("1.EnQueue");
System.out.println("2.DeQueue");
System.out.println("3.Display Queue");
System.out.println("4.Exit");
System.out.println("Enter your
choice:"); ch=sc.nextInt(); switch(ch)
{ case 1:
System.out.println("Enter the element to insert:");
data=sc.nextInt();
q.enQueue(data);
break;
case 2:
data=q.deQueue(); if(data!=-
1)
System.out.println("Deleted
Element:"+data); break; case 3:
q.display();
break;
} }while(ch<4);
}
}
OUTPUT:
EXECUTION I:
TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Queue Using an Array is O(1)
The Time Complexity for Deleting an Element in a Queue Using an Array is O(1)
The Time Complexity for Queue isFUll() Using an Array is O(1)
The Time Complexity for Queue is isEmpty() Using an Array is O(1)
The Time Complexity for Displaying N Elements is O(N)
EXACT TIME COMPLEXITY:
The Exact Time Complexity for Inserting an Element in a Queue Using an Array is O(1)
The Exact Time Complexity for Deleting an Element in a Queue Using an Array is O(1)
The Exact Time Complexity for Queue isFUll() Using an Array is O(1)
The Exact Time Complexity for Queue is isEmpty() Using an Array is O(1)
The Exact Time Complexity for Displaying N Elements is O(5)
RESULT:
Thus, the program for Queue Operations been executed and verified successfully.
EX. NO: 13 QUEUE USING LINKED LIST
DATE :
Aim:
To write a Java function to perform the enqueue operation and dequeue in the Queue
using a Linked List and specify its Time Complexity.
▪Push the integer onto the stack using the push method. o
variable).
▪ Print a message indicating the creation of the stack using a
linked list.
method.
● Display a menu with the options: Enqueue, Dequeue Display, and Exit using
Switch Statement
● Take user input for the chosen option.
● Call the corresponding operation based on User’s Choice ● Repeat the menu
until the user chooses to Exit.
ALGORITHM I: Creating the Enqueue Function
STEP 1: Include the parameter “data” with integer datatype
STEP2: Check whether the queue is full using the isFull() method by the “If”
Statement.
STEP3: If the queue is full, display a message prompting “Queue is Overflow.
Not Possible to insert in Full Queue”
STEP4: If the Queue is not full, increment the rear pointer by 1 and insert the
data at the new rear position in the Queue array
STEP5: Display a message prompting “Element is inserted”
ALGORITHM II: Creating the Dequeue Function
STEP 1: Initialize data of Integer data type to a default value (e.g., -1)
STEP 2: Check whether the Queue is empty using the isEmpty() method by “If”
Statement
STEP 3: If the queue is empty, display a message prompting “Queue is Underflow.
No elements to be deleted in Empty Queue”
STEP 4: If the Queue is not empty, retrieve the element at the front of the queue,
increment the front pointer, and store the data
STEP 4.1:Return the data, which will either be the retrieved element or the default
value if the Queue is empty
TIME COMPLEXITY:
The Time Complexity for Inserting an Element in a Queue Using an LinkedList is O(1)
The Time Complexity for Deleting an Element in a Queue Using an LinkedList is O(1)
The Time Complexity for Queue isFUll() Using an LinkedList is O(1)
The Time Complexity for Queue is isEmpty() Using an LinkedList is O(1)
The Time Complexity for Displaying N Elements is O(N)
RESULT:
Thus, the program for Queue Operations been executed and verified successfully.
EX. NO: 14 BINARY SEARCH
DATE :
Aim:
To write a Java function to Search the number using the Binary Search Method and
specify its Time Complexity.
TASK 1: Creating the Class “BinarySearch”
● Import the util package
● Create a class named” BinarySearch”.
TASK 2: Creating the Main Function
● Display a message prompting the user to enter the Size of the elements for
Binary Search.
● Using the “scanner class” object “in” get the input size for Binary Search and
Assign the input received from the input source to an integer variable “n”.
● Create an Array number to store the integers
● Display a message prompting the user to enter the integer elements for Binary
Search.
● Iterate through user inputs Using “For Loop” o check whether each input is
ALGORITHM:
Implement the BinarySearchIterative Function.
STEP 1:Include the parameter integer array “A” and “data” to perform the Search operation.
STEP 2:Initialize the variable“low” to “0” and the variable “high” to the length of the array
minus 1.
STEP 3: Check whether the “low”is less than or equal to “high” using “While” loop.
a. Midpint: Calculate the midpoint(mid) as (low + high) / 2.
b. Compare: If the value at the midpoint is equal to the target, return the mid
value as the position of the key element.
c. Adjust boundaries:
i. If the value is less than the target, set low to midpoint + 1.
ii. If greater, set high to midpoint - 1.
STEP 4: If the loop ends, the target is not in the array.
CODE:
import java.util.*; public class
BinarySearch { public static void
main(String[] args)
{
System.out.print("BINARY SEARCH\n");
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF
ELEMENTS:"); int n=in.nextInt(); int[] numbers=new int[n];
System.out.println("ENTER THE INTEGER VALUES:");
for(int i=0;i<n;i++)
{
if(in.hasNextInt())
numbers[i]=in.nextInt();
else
{
System.out.println("Enter integer numbers only");
System.exit(0);
}
}
System.out.println("ENTER THE KEY VALUE TO BE SEARCHED IN BINARY SEARCH
LIST"); int key =
in.nextInt();
int res=BinarySearchIterative(numbers,key); if(res==-
1)
System.out.println(key + " IS NOT FOUND");
else
System.out.println(key + " FOUND IN THE ARRAY AT POSITION "+(res+1));
in.close();
}
public static int BinarySearchIterative(int[] A, int data) {
int low = 0, high = A.length-1,mid;
while (low <= high) {
TIME COMPLEXITY:
The Time Complexity to find an Element in an Array using Binary Search is O(Log N)
RESULT:
Thus, the program for finding an Element in an Array using Binary Search has been executed
and verified successfully.
TIME COMPLEXITY:
The Time Complexity to sort the Array using Selection Sort is O(N2)
RESULT:
Thus, the program for sorting an element using Selection sort has been executed and verified
successfully.