Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab Manual Shaheer

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

LAB MANNUAL
DATA
SRRUCTURE AND
ALGORITHM
NAME:
Muhammad Shaheer
STUDENT ID:
CSC-21F-081
SECTION:
3B
COURSE SUPERVISOR:
SYEDA NAZIA ASHRAF
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

LAB No: 1 Lab Assignment

Largest Element in Array Find the largest element in array using the
Objective above two algorithms.
To find the largest element in an
Array.
PROGRAM 1
Algorithm import java.util.Scanner;
A nonempty array DATA with N numerical
values is given. This algorithm finds the public class largestEIN {
location LOC and value MAX of the largest public static void main(String[] args) {
element of DATA. The variable K is used as
a counter. int[] array = new int[100];
int NUM , LOC = 0;
Step 1: [Initialize] set K: =1, LOC: =1 and Scanner scan = new Scanner
MAX: =DATA [1] (System.in);
Step 2: [Increment counter] set K: =K+1. System.out.println("ENTER
Step 3: [Test counter] if K>N, then THE NUMBERS OF ELEMENTS IN
Write LOC, MAX, and Exit. ARRAY");
[End of If structure] NUM = scan.nextInt();
Step 4: [Compute and update] if System.out.println("ENTER
MAX<DATA [K], then
" + NUM + " INTEGERS");
Set LOC: =K and MAX: =DATA
for(int i=0; i < NUM; i++)
[K].
[End of If structure] {
Step 5: [Repeat loop] Go to step 2 array[i] =
[GOTO - To link one line with another.] scan.nextInt();
}
OUTPUT int MAX=array[0];
int MIN=array[0];
for(int i=0;i<NUM;i++ )
{
if (MAX < array[i]) MAX =
array[i];
else if(MIN > array[i]) MIN =
array[i];
}
System.out.println("LARGEST
ELEMENT IS :" + MAX);
System.out.println("SMALLEST
ELEMENT IS :" + MIN);
}

}
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

LAB No: 2(A) data in array\n");


Scanner data = new
Scanner(System.in);
Linear and Binary Search of int index = 0;
an Array int input = 0;
while (true) {
Objective System.out.print("\nEnter
To find the element in an Array using value for Array [" + index + "]: ");
Linear Search try {
input = data.nextInt();
Algorithm (Linear Search) } catch (Exception ex) {
System.out.println("\n\
A Linear DATA with N elements n" + "Your Array" + "\n");
and a specific ITEM of System.out.println("\n"
information are given. This + arr);
algorithm finds the location LOC Scanner data2 = new
of ITEM in array DATA or sets Scanner(System.in);
LOC=0. System.out.println("Ent
1. [Initialize] Set k:=1 and er element that you want me to
LOC:=0. search");
2. Repeat Step 3 and 4 while input = data2.nextInt();
LOC=0 AND k<=N. boolean found = false;
3. If ITEM = DATA[k], for (int i = 0; i <
then: arr.size(); i++) {
Set LOC:=k. if (arr.get(i) == input)
4. Else {
Set k:=k+1. System.out.println(
[Increments counter] "Element " + input + " found at
[End of If Structure.] index " + i);
[End of Step 2 loop.] found = true;
5. [Successful?] break;
If LOC=0 then: }
Write: ITEM is not in }
the array DATA. if (found = false) {
Else System.out.println("E
Write: LOC is the lement not found in array");
location of ITEM. }
[End of If structure] break;
6. Exit }
arr.add(index, input);
PROGRAM index++;

ArrayList<Integer> arr = new }


ArrayList<>();
System.out.println("\nEnter
'n' when you want to stop pushing
Output:
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

2. Repeat Steps 3 and 4 while START ≤


END AND A[MID]≠SKEY.
3. If SKEY< A[MID], then:
Set END:=MID-1.
Else
Set START:=MID+1.
[End of If Structure.]
4. Set MID:=INT((START +END)/2).
[End of Step 2 loop.]
5. If A[MID]= SKEY, then:
Set LOC:= MID
Else:
Set LOC := NULL
[End of If structure.]
6. Exit

PROGRAM 1
import java.util.Scanner;
public class BinaryS {
public static void main(String[] args) {
L
AB No: 2(B)
Objective int[] a = new int[100];
int i, NUM;
To find the element in an Array using
Binary Search Scanner scan = new
Scanner(System.in);
Algorithm (Binary Search)
System.out.println("ENTER THE
Here A is a sorted Linear Array with N NUMBERS OF ELEMENTS IN ARRAY");
elements and SKEY is a given item of
NUM = scan.nextInt();
information to search. The variables
START, END and MID denote, System.out.println("ENTER ARRAY
respectively, the beginning, end and middle ELEMENTS:");
locations of a segments of element of A.
This algorithm finds the location LOC of for (i = 0; i < NUM; ++i) {
SKEY in A or sets LOC= NULL.
a[i] = scan.nextInt();
BinarySearch (A, SKEY) }
1. [Initialize segment variables.] System.out.print("ENTER ELEMENT
Set START:=0, END:=N-1 and FOR SEARCHING:");
MID=INT((START+END)/2).
NUM = scan.nextInt();
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

for (i = 0; i < NUM; i++) { Objective


Perform Bubble Sort
if (a[i] == NUM) {
break; Algorithm (Bubble Sort) BUBBLE
}
(DATA, N)
Here DATA is an array with N elements.
} This algorithm sorts the elements in DATA.
if (i < NUM) { 1. Repeat step 2 and 3 for K=1 to N-1
2. Set PTR :=1. [Initialize pass
System.out.print("ELEMENT FIND pointer PTR.]
AT INDEX " + i); 3. Repeat While PTR ≤ N-K:
[Executes pass.]
} else {
If DATA[PTR] >
System.out.print("ERROR"); DATA[PTR+1], then
[Interchange DATA[PTR]
} and DATA[PTR+1]]
} temp = DATA[PTR]
          DATA[PTR] =
} DATA[PTR+1]
     DATA[PTR+1] = temp;
OUTPUT [End of If structure]
[End of Step 3 inner loop.]
Set PTR:= PTR+1.
[End of Step 1 outer loop.]
4. Exit.

LAB TASK
Perform Bubble Sort with help of array.

PROGRAM 1
import java.util.Scanner;

public class BubbleS {


public static void main(String[] args) {
int[] array = new int[100];
int n = array.length, temp = 0;
Scanner scan = new
LAB No: 3 Scanner(System.in);
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

System.out.println("ENTER NUMBER OUTPUT


OF ELEMENTS IN ARRAY");
n = scan.nextInt();
System.out.println("ENTER " + n + "
INTEGER");
for (int i = 0; i < n; i++) {
array[i] = scan.nextInt();
}
for (int i = 1; i < n; ++i) {
for (int j = 0; j < (n - i); ++j) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Array after bubble
sort:");
for (int i = 0; i < n; ++i) {
System.out.println(array[i]);
Lab 4
}
Objective
} To understand the basic concepts of
} Insertion and Deletion in array.
Algorithm to Insert Element in un-
ordered Array is as follows:

DATA is unsorted linear array with N


elements. LOC is the location where ITEM
is to be inserted where LOC ≤ N. This
Algorithm inserts an element ITEM into the
LOCth position in array DATA.
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

INSERT (DATA, N, I, ITEM, LOC) Scanner scan = new


Scanner(System.in);
1. Set I:=N
[Initialize counter] System.out.println("ENTER NUMBER
2. Repeat the step 3 and 4 while I ≥ LOC OF ELEMENTS IN ARRAY");
3. Set DATA[I+1]:=DATA[I]
n = scan.nextInt();
[Move Ith elements downward or forward]
4. Set I=I-1 System.out.println("ENTER " + n + "
[Decrease counter by 1] INTEGER");
[End of while loop]
5. Set DATA[LOC]=ITEM for (int i = 0; i < n; i++) {
[Insert Element]
array[i] = scan.nextInt();
6. Set N=N+1
[Reset N] }
7. Exit
System.out.print("WHAT POSITION
Algorithm to Delete Element from Array OF ELEMENT YOU WANT TO DELETE:
is: ");

DELETE (DATA, N, I, ITEM, LOC) position = scan.nextInt();


for (int i = position; i < n - 1; i++) {
1.Set ITEM=DATA[LOC]
[Assign en Element to be deleted to ITEM] array[i] = array[i + 1];
2. Repeat for I=LOC to N-1
3. Set DATA[I]:=DATA[I+1] }
[Move the I+1st Element upward or n = n - 1;
backward]
[End of For loop] System.out.println("AFTER
4. Set N:=N-1 DELETING THE ELEMENT: ");
[Reset N]
5. Exit. for (int i = 0; i < n; i++) {
System.out.println("a[" + i + "] = " +
PROGRAM 1 array[i]);
import java.util.Scanner; }
}
public class DeletionIArray { }

OUTPUT
public static void main(String[] args) {
int[] array = new int[100];
int n, position;
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

position = scan.nextInt();
for (int i = n - 1; i >= position; i--) {
array[i + 1] = array[i];
}
System.out.println("WHAT
ELEMENT YOU WANT TO INSERT");
number = scan.nextInt();
n = n + 1;
array[position] = number;
System.out.println("AFTER
INSERTING THE ELEMENT");
for (int i = 0; i < n; i++) {
System.out.println("a[" + i + "] = " +
PROGRAM 2 array[i]);
import java.util.Scanner;
}
public class InsertionIArray {
}
public static void main(String[] args) {
}
int[] array = new int[100];
int n, position, number;
OUTPUT

Scanner scan = new


Scanner(System.in);
System.out.println("ENTER NUMBER
OF ELEMENTS IN ARRAY");
n = scan.nextInt();
System.out.println("ENTER " + n + "
INTEGER");
for (int i = 0; i < n; i++) { LAB No: 5A
array[i] = scan.nextInt(); Objective:
} Sort an array using Selection Sort.

System.out.println("WHAT POSITION Algorithm: (Selection Sort) SELECTION


YOU WANT TO INSET ELEMENT: "); (A, N)
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

This algorithm sorts the array A with N array[k] = array[k - 1];


elements. }
1. Repeat steps 2 and 3 for K=0 to N-2: break;
[Find LOC of the smallest element }
from A[uo }
2. find minimum element in array A] } else {
3. [Interchange A[K] and A[LOC].]
continue;
Set TEMP: = A[K], A[K] = A[LOC]
}
and A[LOC] := TEMP.
[End of step 1 loop.] array[index] = element;
4. Exit. }
System.out.println("SORTED
PROGRAM : ARRAY:");
for (int i = 0; i < n; i++) {
import java.util.Scanner;
System.out.print(array[i] + " ");
public class Selectionsort { }
}
public static void main(String[] args) {
}
// TODO code application logic here OUTPUT
int[] array = new int[100];
int n = array.length, element, index = 0;
Scanner scan = new
Scanner(System.in);
System.out.println("ENTER NUMBER
OF ELEMENTS IN ARRAY");
n = scan.nextInt();
System.out.println("ENTER " + n + "
INTEGER");
for (int i = 0; i < n; i++) {
array[i] = scan.nextInt();
}
for (int i = 1; i < n; i++) {
element = array[i];
if (element < array[i - 1]) { LAB No: 5B
for (int j = 0; j <= i; j++) { Objective:
if (element < array[j]) { Sort an array using Insertion Sort.
index = j; Algorithm: (Insertion Sort) INSERTION
for (int k = i; k > j; k--) { (A, N)
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

This Algorithm sorts an array A with N } } } else {


elements. continue;
-1: second } array[index] = element;
element A[1] to A[N-1]to last element.] }
2. Set TEMP := A[K] and PTR =K-1. System.out.println("SORTED ARRAY:");
[an inner loop which is essentially controlled by for(int i = 0; i < n; i++) {
the variable PTR to locate hole position for the System.out.print(array[i] + " ");
element to be inserted] }
3. Repeat while PTR>= 0 and TEMP <
A[PTR] [check whether the adjacent
element in left side is greater or less than the OUTPUT
current element]
a) Set A[PTR+1] := A[PTR]. [Move
all the left side elements one position
forward, which are greater than key
TEMP.]
b) Set PTR := PTR -1.[End of step 3
loop.]
4. Set A[PTR+1] :=TEMP. [Move
(Insert) current element in its proper place
(hole position).]
[End of Step 1 loop.]
5 Return.

PROGRAM :
int[] array = new int[100];
int n=array.length ,element,index=0;
Scanner scan = new Scanner (System.in);
System.out.println("ENTER NUMBER OF
ELEMENTS IN ARRAY");
n = scan.nextInt();
System.out.println("ENTER " + n + " INTEGER");
for( int i=0; i < n; i++) {
array[i] = scan.nextInt();
} for(int i = 1; i < n; i++) {
element = array[i];
if(element < array[i - 1]) {
for(int j = 0; j <= i; j++) {
if(element < array[j]) {
index = j; LAB 6
for(int k = i; k > j; k--) {
array[k] = array[k - 1]; Objective
} break; Perform Matrix Addition, Multiplication
operations.
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

Matrix Multiplication Algorithm PROGRAM 1 (MATRIX


Matmula (A,B,C,M,P,N) MULTIPLICATION)
Let A be an M X P matrix array, and let B
be a P X N matrix array. This algorithm import java.util.Scanner;
stores the product of A and B in an MXN
public class MatrixMul {
matrix array C.
1. Repeat step 2 to 4 for I=1 to M:
2. Repeat step 3 AND 4 for J=1 to
N: public static void main(String[] args) {
3. Set C[I,J]:=0. Scanner scan = new
[Initializes C[I,J]. ] Scanner(System.in);
4. Repeat for K=1 to P:
[loop grants the no. of columns of int f_row, f_col, s_row, s_col;
second matrix] System.out.print("ENTER NO OF
C[I,J]:=C[I,J] ROWS OF FIRST MATRIX : ");
+A[I,K]*B[K,J] [no. of rows of
second matrix =no. of f_row = scan.nextInt();
System.out.print("ENTER NO OF
columns of first matrix]
COLOMNS OF FIRST MATRIX : ");
[End of inner loop.]
[End of step 2 middle loop.] f_col = scan.nextInt();
[End of step 1 outer loop.]
System.out.print("ENTER NO OF
5. Exit. ROWS OF SECOND MATRIX : ");
Matrix Addition Algorithm s_row = scan.nextInt();
MatAdd(A,B,C,M,N) System.out.print("ENTER NO OF
1 Repeat for I=1; to M COLOMNS OF SECOND MATRIX : ");
2 Repeat for J=1 to N
C[I][J]= A[I][J]+ B[I][J] s_col = scan.nextInt();
[End of inner loop.] if (f_col != s_row) {
[End of outer loop.]
3 Exit. System.out.println("ORDER OF
MATRIX IS INCORRECT ");
Transpose of Matrix Algorithm
} else {
Transpose (A,M,N)
int[][] first = new int[f_row][f_col];
1 Repeat for I=1; to M
2 Repeat for J=1 to N int[][] second = new int[s_row]
C[J][I]= A[I][J] [s_col];
[End of inner loop.]
[End of outer loop.] int[][] result = new int[f_row]
3 Exit [s_col];
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

System.out.println("ENTER THE System.out.println();


ELEMENTS OF FIRST MATRIX : ");
}
for (int i = 0; i < f_row; i++) {
}
for (int j = 0; j < f_col; j++) {
}
first[i][j] = scan.nextInt();
}
OUTPUT
}
System.out.println("ENTER THE
ELEMENTS OF SECOND MATRIX : ");
for (int i = 0; i < s_row; i++) {
for (int j = 0; j < s_col; j++) {
second[i][j] = scan.nextInt();
}
}
for (int i = 0; i < f_row; i++) {
for (int j = 0; j < s_col; j++) {
for (int k = 0; k < f_col; k++) {
result[i][j] += first[i][k] *
second[k][j];
}
}
}

System.out.println("MULTIPLICATION
OF TWO MATRICS IS : ");
for (int[] row : result) {
for (int column : row) {
System.out.print(column + "
"); PROGRAM 2 (MATRIX ADDITION)
} import java.util.Scanner;
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

public class MatrixAddition { for (int i = 0; i < row; i++) {


public static void main(String[] args) { for (int j = 0; j < col; j++) {
// TODO code application logic here result[i][j] = first[i][j] + second[i]
[j]; //use - for subtraction
Scanner scan = new
Scanner(System.in); System.out.print(result[i][j] + " ");
int row, col; }
System.out.print("ENTER NO OF System.out.println();
ROWS OF MATRIX : ");
}
row = scan.nextInt();
}
System.out.print("ENTER NO OF
}
COLOMNS OF MATRIX : ");
col = scan.nextInt(); OUTPUT
int[][] first = new int[row][col];
int[][] second = new int[row][col];
int[][] result = new int[row][col];
System.out.println("ENTER THE
ELEMENTS OF FIRST MATRIX : ");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
first[i][j] = scan.nextInt();
}
}
System.out.println("ENTER THE LAB No: 7
ELEMENTS OF SECOND MATRIX : ");
Objective
for (int i = 0; i < row; i++) { Write program to create a
Link List and perform different
for (int j = 0; j < col; j++) { functionality related to it as stated
below:
second[i][j] = scan.nextInt();
} Algorithm: (Traversing a Link List) Let
LIST be a link list in memory. This
} Algorithm traverses LIST, applying an
System.out.println("Result: "); operation PROCESS to each element of
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

LIST. The variable PTR points to the node 2. Repeat Step 3 while PTR≠NULL:
currently being processed. 3. If ITEM < INFO[PTR], then:
Set PTR:=LINK[PTR].
1. Set PTR:=START.[Initializes pointer [PTR now points to the next node]
PTR.] Else If ITEM=INFO[PTR],then
2. Repeat step 3 and 4 while Set LOC:=PTR, and Exit.
PTR≠NULL. [Search is successful.]
3. Apply PROCESS to Else:
INFO[PTR]. LOC:=NULL , and Exit.
4. Set PTR=LINK[PTR]. [PTR [ITEM now exceeds INFO[PTR].]
now points to the next node.] [End of If structure.]
[End of Step 2 loop.] [End of Step 2 loop.]
5. Exit 4. Set LOC:=NULL.
5. Exit.
Algorithm: SEARCH (INFO,
LINK,START, ITEM, LOC)
Assignment:
LIST is a linked list in the memory. This Write a program to create, display and
algorithm finds the location LOC of the search an element in a Single Link List.
node where ITEM first appear in LIST, or
PROGRAM 1
sets LOC=NULL.
public class linklistSD {
public static void
1. Set PTR:=START.
main(String[] args) {
2. Repeat Step 3 while PTR≠NULL:
// TODO code
3. If ITEM = INFO[PTR], then:
application logic here
Set LOC:=PTR, and Exit.
LinkList sList = new
[Search is successful.]
LinkList();
Else:
sList.addNode(1);
Set PTR:=LINK[PTR].
sList.addNode(2);
[PTR now points to the next node]
sList.addNode(3);
[End of If structure.]
sList.addNode(4);
[End of Step 2 loop.]
sList.display();
4. Set LOC:=NULL.
}
[Search is unsuccessful.]
}
5. Exit.
class LinkList {
Algorithm: SRCHSL (INFO,
LINK,START, ITEM, LOC)
class Node {
LIST is sorted list in memory. This
algorithm finds the location LOC of the
int data;
node where ITEM first appear in LIST, or
Node next;
sets LOC=NULL.
public Node(int data) {
this.data = data;
1. Set PTR:=START.
this.next = null;
}
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

}
public Node head = null;
public Node tail = null;

public void addNode(int


data) {
Node newNode = new
Node(data);
if (head == null) {
head = newNode;
tail = newNode; PROGRAM 2
} else {
public class linklistSearch {
tail.next = newNode;
tail = newNode; public static void main(String[] args) {
}
} // TODO code application logic here
SearchLinkedList sList = new
public void display() {
SearchLinkedList();
Node current = head;
if (head == null) { sList.addNode(1);

System.out.println("List is sList.addNode(2);
empty");
sList.addNode(3);
return;
} sList.addNode(4);

System.out.println("Nodes sList.searchNode(2);
of singly linked list: ");
sList.searchNode(7);
while (current != null) {
}
System.out.print(current.dat
a + " -> "); }
current =
current.next;
} class linkSearch {
System.out.println();
}
}
class Node {

OUTPUT int data;


Node next;

public Node(int data) {


DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

this.data = data; break;


this.next = null; }
} i++;
} current = current.next;
public Node head = null; }
public Node tail = null; }
if (flag) {
public void addNode(int data) { System.out.println("Element is
present in the list at the position : " + i);
Node newNode = new Node(data);
}
if (head == null) {
else {
head = newNode;
System.out.println("Element is not
tail = newNode;
present in the list");
} else {
}
tail.next = newNode;
}
tail = newNode;
}
}
OUTPUT
}

public void searchNode(int data) {


Node current = head;
int i = 1;
boolean flag = false;
if (head == null) {
System.out.println("List is empty");
LAB No: 8
Objective
} else { Write program to create a Link List
and perform different functionality
while (current != null) { related to it as stated below:
if (current.data == data) { Operations on Link List
a) Insertion in Link List
flag = true; b) Deletion in Link List
c) Algorithm:
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

d) INSFIRST (INFO, LINK , TEMP=LINK[TEMP]


START, AVAIL, LOC, [End of while loop]
ITEM) LINK[TEMP]=NEW [Insert at
e) This algorithm inserts ITEM Last]
as the first node in the list. [End of Else structure]
f) Step 1: [OVERFLOW?] If Step 7: Exit
AVAIL=NULL, then Write:
OVERFLOW, and Exit. Inserting into a Sorted Link List
g) Step 2: [Remove first node (Finding the location at the last
from AVAIL list.] node):
h) Set NEW :=AVAIL and Algorithm:
AVAI L:=LINK[AVAIL]. FINDA (INFO, LINK, START,
i) Step 3: Set INFO[NEW] := ITEM, LOC)
ITEM.. [Copies new data This procedure finds the location
into new node] LOC of the last node in as sorted list
j) Step 4: Set LINK[NEW] := such that INFO[LOC] < ITEM, or
START. [New node now sets LOC=NULL.
points to the original node] Step 1: [List Empty?] If START
k) Step 5: Set START := NEW. =NULL,
[Changes START so it then: Set LOC := NULL, and
points to the new node.] Return.
l) Step 6: Exit. [End of If]
Step 2: [Special case?] If ITEM <
Insertion at Last: INFO[START], [ITEM
Algorithm: not in the list]
INLAST (INFO, LINK, START, then: Set LOC := NULL,
AVAIL, LOC, ITEM,TEMP) and Return.
This algorithm inserts ITEM as the [End of If]
last node. Step 3: Set SAVE : = START and
Step 1: [OVERFLOW?] If PTR := LINK[START]. [Initializes
AVAIL=NULL, then Write: pointers]
OVERFLOW, and Exit. Step 4: Repeat step 5 and 6 while
Step 2: [Remove first node from PTR ≠ NULL.
AVAIL list.] Step 5: If ITEM <
Set NEW :=AVAIL and INFO[PTR], then:
AVAIL:=LINK[AVAIL]. Set LOC : =
Step 3: Set INFO[NEW] := ITEM. SAVE, and Return.
[Copies new data into new node] [End of If structure.]
Step 4: If LOC := NULL, then: Step 6: Set SAVE := PTR and
[Inert as first node.] PTR := LINK[PTR].
Set LINK[NEW] := START and [Updates pointers.]
START := NEW. [End of step 4 loop]
Else: SET TEMP=START Step 7: Set LOC := SAVE, and
Step 5: Repeat step 6 while Return.
LINK[TEMP]!=NULL
Step 6: SET Inserting after a given node:
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

Algorithm: Step 3: Exit.


INSLOC (INFO, LINK, START, DELLAST (LINK, START,
AVAIL, LOC, ITEM) AVAIL, LOC, LOCP)
This algorithm inserts ITEM so that This algorithm deletes the last node.
ITEM follows the node with Step 1: If START==NULL
location LOC or inserts ITEM as the [Check if the List is empty or not]
first node when LOC=NULL. Then Write: UNDERFLOW,
Step 1: [OVERFLOW?] If and Exit
AVAIL=NULL, then Write: Step 2: If LINK[START]=NULL,
OVERFLOW, and Exit. then: [If List have only one node]
Step 2: [Remove first node from Set START=NULL
AVAIL list.] [Deletes first node.]
Set NEW :=AVAIL and Set LOC=START
AVAIL:=LINK[AVAIL]. [If list has more than one node]
Step 3: Set INFO[NEW] := ITEM. [End of If Statement]
[Copies new data into new node] Else: SET LOCP=START
Step 4: If LOC := NULL, then:[Inert and LOC=LINK[START] [Set
as first node.] the start pointer
Set LINK[NEW] :=
START and START := NEW. to temporary pointer]
Else: [Insert after node with Step 3: Repeat step 4and 5 while
location LOC.] LINK[LOC]!=NULL [Find the
Set LINK[NEW] := last node]
LINK[LOC] and LINK[LOC] := Step 4: Set LOCP=LOC
NEW. [Move both pointers LOC and
[End of If structure] LOCP forward]
Step 5: Set LOC=LINK[LOC]
DEL (INFO, LINK, START, Step 6: [End of while loop]
AVAIL, LOC, LOCP) SET
This algorithm deletes the node N LINK[LOCP]=NULL
with location LOC. LOCP is the [End of Else structure]
location of the node which precedes Step 7: [Return deleted node to the
N or, when N is the first node, AVAIL list.]
LOCP=NULL. Set LINK[LOC] := AVAIL
Step 1: If LOCP = NULL, then: and AVAIL := LOC.
Set START := Step 8: Exit
LINK[START]. [Deletes first DELETE (INFO, LINK, START,
node.] AVAIL, ITEM)
Else:
Set LINK[LOCP]:= This algorithm deletes from a linked list the
LINK[LOC]. [Deletes node N.] first node N which contains the given ITEM
[End of If structure.] of information.
Step 2: [Return deleted node to the Step 1: [Use procedure FINDB to find the
AVAIL list.] location of N and its preceding node.]
Set LINK[LOC] := AVAIL Call FINDB(INFO, LINK, START,
and AVAIL := LOC. AVAIL, LOC, LOCP)
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

Step 2: If LOC=NULL, then: Write: ITEM }


not in list, and Exit. }
Step 3: [Delete node.]
If LOCP=NULL, then: public void display() {
Set START := LINK[START.] Node current = head;
[Deletes first node.] if (head == null) {
Else
Set LINK[LOCP] := System.out.println("List is
LINK[LOC]. [Deletes node N.] empty");
[End of If structure.] return;
Step 4: [Return deleted node to the AVAIL }
list]
Set LINK[LOC] := AVAIL and System.out.println("Adding
AVAIL := LOC nodes to the start of the list:
Step 5: Exit ");
while (current != null) {

System.out.print(current.dat
PROGRAM 1
a + "-> ");
a) Insert node at Start/First Position in
current =
Singly Linked List current.next;
public class InsertIlink { }
class Node { System.out.println();
}
int data;
Node next; public static void
main(String[] args) {
public Node(int data) { // TODO code
this.data = data; application logic here
this.next = null; InsertIlink sList = new
} InsertIlink();
} sList.addAtStart(1);
public Node head = null; sList.display();
public Node tail = null; sList.addAtStart(2);
sList.display();
public void addAtStart(int sList.addAtStart(3);
data) { sList.display();
Node newNode = new sList.addAtStart(4);
Node(data); sList.display();
if (head == null) {
head = newNode; }
tail = newNode; }
} else {
Node temp = head;
head = newNode;
head.next = temp;
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

OUTPUT public void display() {


Node current = head;
if (head == null) {
System.out.println("List is
empty");
return;
}
System.out.println("Adding
nodes to the end of the list: ");
while (current != null) {
System.out.print(current.data
+ " -> ");
current = current.next;
b) Insert node at Last / End Position in }
Singly Linked List. System.out.println();
}
public class linklistinsertlast {

class Node { public static void main(String[]


args) {
int data; // TODO code application logic
Node next; here
linklistinsertlast sList = new
public Node(int data) { linklistinsertlast();
this.data = data; sList.addAtEnd(1);
this.next = null; sList.display();
} sList.addAtEnd(2);
} sList.display();
public Node head = null; sList.addAtEnd(3);
public Node tail = null; sList.display();
sList.addAtEnd(4);
public void addAtEnd(int data) { sList.display();
Node newNode = new
Node(data); }
if (head == null) { }
head = newNode;
OUTPUT
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

}
size++;
}
public void addInMid(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
C) Insert Node at Middle Position in Singly
Linked List } else {
Node temp, current;
public class insertinmiddle { int count = (size % 2 == 0) ? (size / 2) :
class Node { ((size + 1) / 2);

int data; temp = head;

Node next; current = null;

public Node(int data) { for (int i = 0; i < count; i++) {

this.data = data; current = temp;

this.next = null; temp = temp.next;

} }

} current.next = newNode;

public int size; newNode.next = temp;

public Node head = null; }

public Node tail = null; size++;

public void addNode(int data) { }

Node newNode = new Node(data); public void display() {

if (head == null) { Node current = head;

head = newNode; if (head == null) {

tail = newNode; System.out.println("List is empty");

} else { return;

tail.next = newNode; }

tail = newNode; while (current != null) {


DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

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


current = current.next;
}
System.out.println();
}

public static void main(String[] args) {


// TODO code application logic here
insertinmiddle sList = new
insertinmiddle(); d) Delete node from the beginning of
the linked list.
sList.addNode(1); class Node {
int data;
sList.addNode(2);
Node next;};
System.out.println("Original list: "); class LinkedList {
Node head;
sList.display(); LinkedList(){
sList.addInMid(3); head = null; }
void push_back(int newElement) {
System.out.println("Updated List: "); Node newNode = new Node();
sList.display(); newNode.data = newElement;
newNode.next = null;
sList.addInMid(4); if(head == null) {
head = newNode;
System.out.println("Updated List: ");
} else { Node temp = new Node();
sList.display(); temp = head;
while(temp.next != null)
temp = temp.next;
} temp.next = newNode;} }
void pop_front() {
if(this.head != null) {
Node temp = this.head;
}
this.head = this.head.next;
temp = null; } }
void PrintList() {
Node temp = new Node();
temp = this.head;
OUTPUT if(temp != null) {
System.out.print("The list contains: ");
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next; }
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

System.out.println(); head = new_node; }


} else { void deleteNode(int position) {
System.out.println("The list is if (head == null)
empty."); } } } return;
Node temp = head;
public class Implementation {
if (position == 0) {
public static void main(String[] args) {
head = temp.next;
LinkedList MyList = new LinkedList();
return; }
MyList.push_back(10);
for (int i = 0; temp != null && i < position - 1;
MyList.push_back(20);
i++)
MyList.push_back(30);
temp = temp.next;
MyList.push_back(40);
if (temp == null || temp.next == null)
MyList.PrintList();
return;
MyList.pop_front();
Node next = temp.next.next;
MyList.PrintList();
temp.next
}
= next;
}
} public void printList() {
Node tnode = head;
OUTPUT
while (tnode != null) {
System.out.print(tnode.data + " ");
tnode = tnode.next;
} }
public static void main(String[] args) {
LinkedList llist = new LinkedList();
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
llist.push(8);
System.out.println("\nCreated Linked list
e) Delete node from specific position is: ");
package linklist; llist.printList();
class LinkedList { llist.deleteNode(4);
Node head; System.out.println( "\nLinked List after
class Node { Deletion at position 4: ");
int data; llist.printList(); } }
Node next;
Node(int d) {
OUTPUT
data = d;
next = null; } }
public void push(int new_data)
{
Node new_node = new
Node(new_data);
new_node.next = head;
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

[End of Step 2 loop.]


5. Set value equal to the top element
on stack.
6. Exit.

PROGRAM 1
import java.util.Scanner;
import java.util.Stack;
LAB 9 /**

Objective *
Evaluate Postfix Expression
* @author SHY
Algorithm of Evaluation of Postfix
Expression */
public class Postfixexp {
P postfix expression
1. Add a right parenthesis “)” at the
end of P. [This act as sentinel.]
2. Scan P public static void main(String[] args) {
from left // TODO code application logic here
to right
and
repeat
steps3 Scanner scan = new
and 4 Scanner(System.in);
for each
String EXPRESSION;
element
of P System.out.println("ENTER POSTFIX
until the EXPRESSION :");
sentinel
“)” is EXPRESSION = scan.next();
encoun
System.out.print("ENTER
red,
3. If an operand is encountered, EVALUATION OF THE POSTFIX
put it on stack EXPRESSION " + (EXPRESSION) + "
4. If an operator is encountered, IS :");
then:
evaluatePostfix(EXPRESSION);
(a) Remove the top two elements of stack,
where A is the top element and B is the }
next-to-top element.
(b) Evaluate B [operator] A.
(c) Place the result of static boolean isOperator(char ch) {
(b) on stack.
[End of If structure]
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

if (ch == '+' || ch == '-' || ch == '*' || ch break;


== '/') {
}
return true;
} else {
}
int operand =
return false; EXPRESSION.charAt(i) - '0';
} postFix.push(operand);
}
static void evaluatePostfix(String }
EXPRESSION) {
System.out.println(postFix.pop());
Stack<Integer> postFix = new
}
Stack<Integer>();
}
for (int i = 0; i <
EXPRESSION.length(); i++) { OUTPUT
if
(isOperator(EXPRESSION.charAt(i))) {
int op1 = postFix.pop();
int op2 = postFix.pop();
switch (EXPRESSION.charAt(i))
{
case '+':
postFix.push(op2 + op1);
break;
case '-':
postFix.push(op2 - op1);
break;
case '*':
postFix.push(op2 * op1);
break;
case '/':
postFix.push(op2 / op1);
LAB No: 10
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

* To change this template file, choose Tools


Objective | Templates
Convert Infix to Postfix Expression * and open the template in the editor.
*/
Algorithm
Qarithmetic /**
expression *
P postfix expression * @author SHY
1. Push “(“onto Stack, and add “)” to the */
end of Q. public class infixtopostfix {
2. Scan Q from left to right and repeat
Step 3 to 6 for each element of Q until public static void main(String[] args) {
the stack is empty: // TODO code application logic here
3. If an operand is encountered, add it String exp = "(A+B)*(C-D)";
to P. System.out.println("Infix Expression: "
4. If a left parenthesis is encountered, + exp);
push it onto stack. System.out.println("Postfix Expression:
5. If an operator is encountered, then: " + infixToPostFix(exp));
(a) Repeatedly pop from the }
stack and add to P each
operator (on the top of stack) static int precedence(char c) {
which has the same switch (c) {
precedence as or higher case '+':
precedence than [operator]. case '-':
(b) Add [operator] to stack. return 1;
[End of If structure.] case '*':
6. If a right parenthesis is encountered, case '/':
then: return 2;
(a) Repeatedly pop from the case '^':
stack and add to P each return 3;
operator (on the top of stack) }
until a left parenthesis is return -1;
encountered. }
(b) Remove the left parenthesis.
[Do not add the left static String infixToPostFix(String
parenthesis to P.] expression) {
[End of If structure.] String result = "";
[End of Step2 loop.] Stack<Character> stack = new
7. Exit. Stack<>();
for (int i = 0; i < expression.length(); i+
PROGRAM 1 +) {
import java.util.Stack; char c = expression.charAt(i);
//check if char is operator
/* if (precedence(c) > 0) {
* To change this license header, choose
License Headers in Project Properties.
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

while (stack.isEmpty() == false LAB 11


&& precedence(stack.peek()) >=
precedence(c)) {
Objectives
result += stack.pop();
To write a program to implement Linear
}
Queue data structure using Arrays.
stack.push(c);
} else if (c == ')') {
Insertion in Queue:
char x = stack.pop();
while (x != '(') {
Algorithm: ENQUEUE(QUEUE,
result += x;
MAXSIZE, FRONT, REAR,COUNT,
x = stack.pop();
ITEM)
}
This algorithm inserts an element ITEM into
} else if (c == '(') {
a circular queue.
stack.push(c);
1. [QUEUE already filled?]
} else {
If COUNT = MAXSIZE then: [ COUNT
result += c;
is number of values in the QUEUE]
}
Write: OVERFLOW, and Return.
}
2. [Find new value of REAR.]
for (int i = 0; i <= stack.size(); i++) {
If COUNT= 0, then: [Queue
result += stack.pop();
initially empty.]
}
Set FRONT= 0 and REAR = 0
return result;
Else: if REAR = MAXSIZE - 1, then:
}
Set REAR = 0
}
Else:
Set REAR = REAR+1.
OUTPUT [End of If Structure.]
3. Set QUEUE[REAR] = ITEM. [This
insert new element.]
4. COUNT=COUNT+1
[ Increment to Counter. ]
5. Return.

Deletion in Queue:

Algorithm: DEQUEUE(QUEUE,
MAXSIZE, FRONT, REAR,COUNT,
ITEM)
This procedure deletes an element from a
queue and assigns it to the
variable ITEM.
1. [QUEUE already empty?]
If COUNT= 0, then: Write: UNDERFLOW,
and Return.
2. Set ITEM = QUEUE[FRONT].
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

3. Set COUNT = COUNT -1


4. [Find new value of FRONT.]
int SIZE = 5;
If COUNT = 0, then: [There
was one element and has been deleted ] int items[] = new int[SIZE];
Set FRONT= -1, and REAR =
-1. int front, rear;
Else if FRONT= MAXSIZE, then:
[Circular, so set Front = 0 ]
Set FRONT = 0 Queue() {
Else: front = -1;
Set FRONT:=FRONT+1.
[End of If structure.] rear = -1;
5. Return ITEM
}

PROGRAM 1 boolean isFull() {


public class linearqueue {
if (front == 0 && rear == SIZE - 1) {
return true;
public static void main(String[] args) {
}
// TODO code application logic here
return false;
Queue q = new Queue();
}
q.deQueue();
q.enQueue(1);
boolean isEmpty() {
q.enQueue(2);
if (front == -1) {
q.enQueue(3);
return true;
q.enQueue(4);
} else {
q.enQueue(5);
return false;
q.enQueue(6);
}
q.display();
}
q.deQueue();
q.display();
void enQueue(int element) {
}
if (isFull()) {
}
System.out.println("Queue is full");
} else {
class Queue {
if (front == -1) {
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

front = 0; int i;
} if (isEmpty()) {
rear++; System.out.println("Empty Queue");
items[rear] = element; } else {
System.out.println("Inserted " + System.out.println("\nFront index-> " +
element); front);
} System.out.println("Items -> ");
} for (i = front; i <= rear; i++) {
System.out.print(items[i] + " ");
int deQueue() { }
int element; System.out.println("\nRear index-> " +
rear);
if (isEmpty()) {
}
System.out.println("Queue is empty");
}
return (-1);
}
} else {
element = items[front];
if (front >= rear) { OUTPUT
front = -1;
rear = -1;
} /* Q has only one element, so we reset
the queue after deleting it. */ else {
front++;
}
System.out.println("Deleted -> " +
element);
return (element);
}
}

void display() {
LAB 12
/* Function to display elements of Queue */
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

Object: Implement Merge Sort. }


}
Pseudo code:
Merge(L, R, A) [Merge Merge_Sort(A)
and sort two halves] [divide/partition the array A]
{ {
nL = length of (L) [no.of n = length[A] [store no.of
elements in left] elements in A]
nR = length of (R) [no.of if(n<2) [base or exit
elements in right] condition i.e if only one element in
i=0 [for left array then
L] return and stop portioning/recursion]
j=0 [for return
right R] mid = n/2
k=0 [for left = array of size(mid)
array A] right = array of size(n-mid)
while (i<nl && j<nR) for(i = 0 to mid-1)
{ left[i] = A[i]
if (L[i]<=R[j]) for(i = mid+1 to n-1)
{ right[i-mid] = A[i]
A[k] = L[i]
i = i+1 Merge_Sort(left)
} [recursive call]
else Merge_Sort(right)
{ [recursive call]
A[k] = R[j] Merge(left, right, A)
j = j+1 }
}
k =k+1
} PROGRAM 1
public class mergesort {
while(i<nL) [for leftover
public static void main(String[] args) {
left elements for fill remaining positions of
// TODO code application logic here
k]
int arr[] = {56, 78, 13, 45, 90, 7};
{
System.out.println("Given Array");
A[k] = L[i]
print(arr);
i = i+1
MergeSort ob = new MergeSort();
k = k+1
ob.sort(arr, 0, arr.length - 1);
}
System.out.println("\nSorted array");
printArray(arr);
while(j<nR) [for
}
leftover right elements for fill remaining
}
positions of k]
class MergeSort {
{
void merge(int arr[], int l, int m, int r) {
A[k] = R[j]
int n1 = m - l + 1;
j = j+1
int n2 = r - m;
k = k+1
DATA STRUCTURE & ALGORITM LAB MANNUAL MAA’M SYEDA NAZIA ASHRAF

int L[] = new int[n1]; }


int R[] = new int[n2];
for (int i = 0; i < n1; ++i) { OUTPUT
L[i] = arr[l + i];
}
for (int j = 0; j < n2; ++j) {
R[j] = arr[m + 1 + j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
sort(arr, l, m);
sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
static void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

You might also like