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

DSA All Labs

The document describes a lab on ArrayLists and Vectors in Java. It includes 4 sample programs: 1) An ArrayList example that adds and displays string elements and inserts an element at a specific position. 2) An ArrayList example that adds integer elements and displays them in a for-each loop. 3) A Vector example that creates a Vector and adds string elements using the add method. 4) The document provides tasks for students to complete related to ArrayLists and Vectors in Java.

Uploaded by

Nabiha Mirza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views117 pages

DSA All Labs

The document describes a lab on ArrayLists and Vectors in Java. It includes 4 sample programs: 1) An ArrayList example that adds and displays string elements and inserts an element at a specific position. 2) An ArrayList example that adds integer elements and displays them in a for-each loop. 3) A Vector example that creates a Vector and adds string elements using the add method. 4) The document provides tasks for students to complete related to ArrayLists and Vectors in Java.

Uploaded by

Nabiha Mirza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 117

SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 01

Introductory to Java String ADT and I/O Classes, Wrapper Classes


and Filing in JAVA
Object
To implement Java Built-In String Class, User input and Filing.

Class Activity:

Sample Program#1

import java.util.Scanner;
class ScannerTest{

public static void main(String args[])


{ Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+"
fee:"+fee); sc.close(); } }

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Sample Program#2
This program uses different string classes.

import java.io.*;
/** The Names class provides a single function, main, that will
* perform various manipulations of the name abc ijk xyz.

class Names {
/** Performs various string operations on the name ana kim xen.

public static void main(String arg[]) {


String first = "ana";
String middle = "kim";
String last = "xen";
String initials;
String firstInit, middleInit, lastInit;

firstInit = first.substring(0,1);
middleInit = middle.substring(0,1);
lastInit = last.substring(0,1); initials
= firstInit.concat(middleInit); initials
= initials.concat(lastInit);

System.out.println()
System.out.println(first + " " + middle + " " + last + " ");
System.out.println(initials);
System.out.println(last + ", " + first + " " + middle);
System.out.println(last + ", " + first + " " + middleInit +".");
System.out.println(first.toUpperCase() + " " + last.toUpperCase);
System.out.println(first + " equals ana is " + first.equals("ana"));
System.out.println(first + " equals ana (ignoring case) is " + first.equalsIgnoreCase("ana"));
System.out.println("The character at index 3 in " + middle + " is " +middle.substring(3,1));
System.out.println("The index of \"gerald\" within " + middle + " is " +
middle.indexOf("gerald"));
System.out.println("The index of \"gerald\" within " + last + " is " +last.indexOf("gerald"));
System.out.println();

}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:

Sample Program#3

public class MyClass { public static void


main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Sample Program#4

import java.io.*;

public class FileStreamTest{

public static void main(String args[])


File f;

try{
byte bWrite [] = {65,66,67,68,69}; f =new
File("D:/filing/test.txt");
OutputStream os = new FileOutputStream(f);
for(int x=0; x < bWrite.length ; x++)
{ os.write( bWrite[x] ); // writes the bytes
} os.close();

InputStream is = new FileInputStream(f);


int size = is.available();

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


System.out.print((char)is.read() + " ");
} is.close();
}
catch(IOException e){
System.out.print("Exception");
}
} }

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Lab Tasks
1. Write a program that takes your name, section and GPA as input and print it.

Code:
import java.util.Scanner; public class lab1{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.println("Enter Your Name : ");


String name = input.nextLine();

System.out.println("Enter Your GPA : ");


String gpa = input.nextLine();

System.out.println("Enter Your Section : ");


String Sec = input.nextLine();

}
} Output:

2. Write a program that initialize five different strings and perform the following operations.
a. Concatenate all five stings
b. Convert first one string to uppercase
c. Convert fourth string to lowercase
d. Find the substring from the concatenated string from 8 to onward
e. Find the substring from the concatenated string from 2 to onward

Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

package lab;
public class lab1 {
public static void main(String[] args) {
String a = "Hello ", b = "To ", c = "A ", d = "Programming World", e = "!!";

String last = (a.concat(b).concat(c).concat(d).concat(e));


System.out.println("Concatenate all five stings : "+last);
System.out.println("Convert first one string to uppercase : "+a.toUpperCase());
System.out.println("Convert fourth string to lowercase : "+d.toLowerCase());
System.out.println("concatenated string from 8 to onward : "+last.substring(8,last.length()));
System.out.println("concatenated string from 2 to onward : "+last.substring(2,last.length()));
}

}
Output:

3. Write a program that takes three numbers as input write it on a file and then read from the file
and print it.

Code:
package lab1;
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args){
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter Number1: ");
int no1 = input.nextInt();
System.out.print("Enter Number2: ");
int no2 = input.nextInt();
System.out.print("Enter Number3: ");
int no3 = input.nextInt();
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\myfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("Number1: "+no1+"\nNumber2: "+no2+"\nNumber3: "+no3);
bw.close();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.println("Reading from file:");


BufferedReader br = new BufferedReader(new FileReader(f));
String s;
while ((s = br.readLine()) != null){
System.out.println(s);
}
br.close();
}catch(Exception e){
e.printStackTrace();

}
}
}
Output:

Notepad:

4. Write a program that takes three numbers as input write it on a file and then read from the file,
convert them into character and print it

Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

package lab1;
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args){
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter no1: ");
int no1 = input.nextInt();
System.out.print("Enter no2: ");
int no2 = input.nextInt();
System.out.print("Enter no3: ");
int no3 = input.nextInt();
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\myfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write(no1+"\n"+no2+"\n"+no3);
bw.close();
System.out.println("Reading from file:");
BufferedReader br = new BufferedReader(new FileReader(f));
String s;
while ((s = (br.readLine())) != null){
int i = Integer.parseInt(s);
System.out.println((char)i);
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
Output:

Notepad:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Home Tasks
1. Write a program that take string as an input attempting to guess the secret word enters
letters one at a time. After each guess, the guess template is updated (if necessary) to
show which letters in the secret word match the letter guessed. This process continues
until the guess template matches the secret word choice of 7 wrong attempts. The
number of guesses is then output. For example:

Enter the secret word: test


----
Guess a letter: a
----
Guess a letter: e
-e--
Guess a letter: n
-e--
Guess a letter: s
-es-
Guess a letter: t test=test
You guessed the word in 5 guesses.
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 02
Array List and Vector in JAVA

Object
To implement Array List and Vector.

Lab Activity:

Sample Program#1

import java.util.*; class JavaExample{


public static void main(String args[]){
ArrayList<String> alist=new ArrayList<String>();
alist.add("Steve"); alist.add("Tim");
alist.add("Lucy"); alist.add("Pat");
alist.add("Angela");
alist.add("Tom");

//displaying elements
System.out.println(alist);

//Adding "Steve" at the fourth position alist.add(3, "Steve");

//displaying elements
System.out.println(alist);
} }

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Sample Program#2
import java.util.ArrayList; public class

Main {public static void main(String[] args)

ArrayList<Integer> myNumbers = new

ArrayList<Integer>(); myNumbers.add(10);

myNumbers.add(15); myNumbers.add(20);

myNumbers.add(25); for (int i : myNumbers) {

System.out.println(i);

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Sample Program#3
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new
Vector<String>(); //Adding elements using
add() method of List vec.add("Tiger");
vec.add("Lion"); vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of
Vector vec.addElement("Rat");
vec.addElement("Cat"); vec.addElement("Deer");

System.out.println("Elements are: "+vec);


}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Sample Program#4
import java.util.*;
public class VectorExample2 {
public static void main(String args[]) {
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);
//Display the vector elements
System.out.println("Values in vector: " +in);
//use remove() method to delete the first occurence of an element
System.out.println("Remove first occourence of element 200: "+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " +in);
//Remove the element at index 4
System.out.println("Remove element at index 4: " +in.remove(4));
System.out.println("New Value list in vector: " +in);
//Remove an element
in.removeElementAt(5);
//Checking vector and displays the element
System.out.println("Vector element after removal: " +in);
//Get the hashcode for this vector
System.out.println("Hash code of this vector = "+in.hashCode());
//Get the element at specified index
System.out.println("Element at index 1 is = "+in.get(1));
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:

Lab Tasks
1. Write a program that initializes ArrayList which initializes 10 integers in it. Display all the
integers and sum of these integers.

Code:
package lab1;
import java.util.*;
public class lab1{
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
arr.add(6);
arr.add(7);
arr.add(8);
arr.add(9);
arr.add(10);
int count = 0;
for (int i:arr){
count += i;
}
System.out.println("Sum of Numbers: "+count);
}

}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:

2. Write a program that initialize Vector of String data type. Initialize 10 strings in it and perform
all the operations on it.

Code:

package lab1;
import java.util.*;
public class lab1{
public static void main(String[] args) {
Vector<String> x = new Vector<>();
x.add("Nabiha");
x.add("Hunaina");
x.add("Huzaifa");
x.add("Hanif");
x.add("Sobia");
x.add("Seemla");
x.add("Radeef");
x.add("Amna");
x.add("Bisma");
x.add("Aimen");
System.out.println("Elements are : "+x);
System.out.println("After removing a element :"+x.remove(3));
System.out.println("Element at index 1 is : "+x.get(1)); x.add("Hafsa");
System.out.println("After Adding Element : "+x);
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Home Tasks
1. Create a ArrayList storing string objects. Write a menu driven program which:

a. Displays the all the elements


b. Displays the largest String

Code:
package lab1;
import java.util.*;
public class lab1 {
public static void main(String[] args)
{ ArrayList<String> menu = new ArrayList<>();
menu.add("Cold drink");
menu.add("Tikka");
menu.add("Biryani");
menu.add("Cheesy fries");
menu.add("wings");
System.out.println("\tMenu :");
for(String s:menu){ System.out.println("~"+s);
}
int biggest = 0,
index = 0;
for(int i = 0; i< menu.size(); i++){ String word =
menu.get(i);
if(word.length()>biggest){ biggest = word.length();
index = i;
}
}
System.out.println("Biggest String: "+menu.get(index));
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

2. Create a Vector storing integer objects as an input.


a. Sort the vector
b. Display largest number
c. Display smallest number
Code:
package lab1;
import java.util.*;
public class lab1 { public static void
main(String[] args) {
Scanner input = new Scanner(System.in);
Vector<Integer> nums = new Vector<>();
int big = 0, index = 0;
for (int i = 0; i<5; i++){
System.out.print("Enter Number "+
(i+1)+": ");
int no = input.nextInt();
nums.add(no);
if (no>big){
big = no;
index = i;
}
}
System.out.println("Vector: "+nums);
System.out.println("Biggest Integer:
"+nums.get(index));
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 03
Implementation of Recursive Procedure

Object
To implement
Recursive Procedures.

Sample Program #1

public class Power {

public static void main(String[] args) {

int base = 3, powerRaised = 4;

int result = power(base, powerRaised);

System.out.printf("%d^%d = %d", base, powerRaised, result);

public static int power(int base, int powerRaised) {

if (powerRaised != 0)

return (base * power(base, powerRaised - 1));

else

return 1;

}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:

Lab Tasks
1. Write a program that implements factorial using recursive procedure.
Code:
package lab3;
public class lab3 {
public static void main(String[] args){
System.out.println("Factorial of 5: "+factorial(5));
}
public static int factorial(int n){
if(n==0)
return 1;
return n*factorial(n-1);
}
}

Output:

2. Write a program that implements Fibonacci series using recursive procedure.

Code:
package Lab3;
public class Task2 {
public static void main(String[] args){
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.println("Fibonacci of 7: "+fibonacci(7));
}

public static int fibonacci(int n){


if (n<=1)
return n;
return fibonacci(n-1)+fibonacci(n-2);
}
}

Output:

Home Tasks
1. Write a program that implements Palindrome using recursive procedure.

Code:
package Lab3;
public class Task {
public static void main(String[] args) {
System.out.println("MOM is palindrome: "+palindrome("MOM"));
System.out.println("Moring is palindrome: "+palindrome("Bro"));
}
public static boolean palindrome(String s){
if(s.length()==0|| s.length()==1)
return true;
if(s.charAt(0)==s.charAt(s.length()-1)){
return palindrome(s.substring(1,s.length()-1));
}
return false;
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

2. Write a program to calculate the sum of numbers from 1 to n using


recursion. N should be user input.

Code:
package Lab3;
import java.util.Scanner;
public class Task {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number to check sum: ");
int n = input.nextInt();
System.out.printf("Sum of %d numbers = %d\n",n,sum(n));
}
public static int sum(int n){
if (n==1)
return 1;
return n+sum(n-1);
}
}
Output:

3. Write a program to count the digits of a given number using recursion.

Input: 50
Output: 2 digits
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Code:
package Lab3;
import java.util.Scanner;
public class Task{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Numbers to check digits: ");
int n = input.nextInt();
System.out.printf("%d has : %d digits\n",n,digitsChecker(n));
}
public static int digitsChecker(int n){
if (n==0)
return 0;
return 1+ digitsChecker(n/10);
}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 04
Linear Array Implementation

Object
Implementing linear array and associated methods.

Task
1. Write a program to implement all basic operations in linear array (specified in linear array
class). Write a demo class to show the working of array.

Code:
package Lab4;
public class Task {
public static void main(String[] args) {
int[] arr = new int[5];
int length = arr.length;
for(int i=0; i<length; i++){
arr[i]= i+1;
}
// Traversing Array
for(int i=0; i<length; i++){
System.out.printf("arr[%d] = %d , ",i,arr[i]);
}
// Delting Elements
int k = 2;
for (int i=k; i<length-1; i++){
arr[i] = arr[i+1];
}
length -= 1;
System.out.println("\nArray after deleting Index 2: ");
for(int i=0; i<length; i++){
System.out.printf("arr[%d] = %d , ",i,arr[i]);
}
// Insertion
k = 2;
int j = length-1;
for (int i=j; i>k; i--){
SWE-203L: Data Structures and Algorithms SSUET/QR/114

arr[j] = arr[j-1];
}
arr[k] = 10;
length +=1;
System.out.println("\nArray after Inserting 10 at index 2");
for(int i=0; i<length; i++){
System.out.printf("arr[%d] = %d , ",i,arr[i]);
}
}
}
Output:

2. Add a method in the class that takes array and merge it with the existing one.

Code:
package Lab4;
import java.util.*;
public class Task {
public static void main(String[] args) {
int[] arr1 = {11,12,13,14,15};
int[] arr2 = {16,17,18,19};
System.out.println("Array 1: "+ Arrays.toString(arr1));
System.out.println("Array 2: "+ Arrays.toString(arr2));
int[] arr = merge(arr1,arr2);
System.out.println("Merged Array: " + Arrays.toString(arr));
}
public static int[] merge(int[] arr1, int[] arr2){
int length = arr1.length + arr2.length;
int[] arr = new int[length];
for(int i=0; i<length; i++){
if(i<arr1.length){
arr[i] = arr1[i];
SWE-203L: Data Structures and Algorithms SSUET/QR/114

}else{
arr[i] = arr2[i-arr2.length-1];
}
}
return arr;
}
}
Output:

3. Add a method in the same class that splits the existing array into two. The method should
search a key in array and if found splits the array from that index of the key

package Lab4;
import java.util.*;
public class Task {
public static void main(String[] args) {
int[] array = {11,12,13,14,15,16,17,18,19};
split(array, 3);
}
public static void split(int[] arr, int index){
int[] arr1 = new int[index+1];
int[] arr2 = new int[arr.length-index-1];
for (int i=0; i<arr.length; i++){
if(i<arr1.length){
arr1[i] = arr[i];
}else{
arr2[i-arr1.length] = arr[i];
}
}
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("After splitting at index: "+index);
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Home Task
1. Write a Java program to create all possible permutations of a given array of distinct
integers.   

Example:
Input:
nums1 = {1, 2, 3, 4}
nums2 = {1, 2, 3}

Output:
Possible permutations
of the said array 1:
[1, 2, 3, 4]
[1, 2, 4, 3]
....
[4, 1, 3, 2]
[4, 1, 2, 3]

Possible permutations
of the said array 2:
[1, 2, 3]
[1, 3, 2]
...
[3, 2, 1]
[3, 1, 2]

Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

package Lab4;
import java.util.*;
public class Task {
public static void
main(String[] args)
{
Scanner input =
new
Scanner(System.in
);
int[] arr1 = new
int[3];
System.out.println
("\tArray 1:");
for (int i=0;
i<arr1.length; i++)
{
System.out.print("
Enter element "+
(i+1)+": ");
arr1[i] =
input.nextInt();
}
int[] arr2 = new
int[4];
System.out.println
("\n\tArray2");
for (int i=0;
i<arr2.length; i++)
{
System.out.print("
Enter element "+
(i+1)+": ");
arr2[i] =
input.nextInt();
}
System.out.println
("Permutations of
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Array 1:");
permute(arr1,0);
System.out.println
("\nPermutations
of Array 2:");
permute(arr2,0);
}
static void
permute(int[]
arr,int k){
for(int i = k; i <
arr.length; i++){
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
permute(arr, k+1);
temp = arr[k];
arr[k] = arr[i];
arr[i] = temp;
}
if (k == arr.length
-1){
System.out.println
(Arrays.toString(ar
r));
}
}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 05
Sorting on Linear Array

Object
SWE-203L: Data Structures and Algorithms SSUET/QR/114

To sort a linear array using Selection Sort, Bubble Sort and Merge Sort.

Theory

Sorting is the process of arranging data into meaningful order so that you can analyze it more
effectively. For example, you might want to order sales data by calendar month so that you can
produce a graph of sales performance. You can use Discoverer to sort data as follows:

 sort text data into alphabetical order


 sort numeric data into numerical order
 group sort data to many levels, for example, you can sort on City within Month within

Algorithm for
Selection Sort

This algorithm sorts the array A with N elements.

1.Repeat Step 2 and 3 for K=1 to N-1


2. Call MIN (A, K, N, LOC)
3. [Interchange A[K] and A[LOC]
Set TEMP: =A[K], A[K]:=A[LOC] and
A[LOC]:=TEMP
[End of Step 1 loop]
4.Exit

Algorithm for
Bubble Sort

1. Repeat step 2 -3 for K:=1 to N-1


2. Set PTR :=1
3. Repeat While PTR≤N-K
a) If DATA[PTR] > DATA[PTR+1], then
Interchang
e DATA [PTR]
and DATA
[PTR+1]
[End of if
structure]
b) Set PTR:= PTR+1
[End of Step 3
loop]
[End of Step 1 loop]
4. Exit
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Algorithm for Merge


Sort

MergeSort(arr, left,
right):
if left > right
return
mid = (left+right)/2
mergeSort(arr, left,
mid) mergeSort(arr,
mid+1, right)
merge(arr, left, mid,
right)
end

Lab Task
4. Write a program for Selection sort that sorts an array containing numbers, prints all the sort
values of array each followed by its location.

Code:
package Lab5;
import java.util.*;

public class Task{


public static void main(String[] args){
int[] arr = {18,22,6,10,0,45,35};
System.out.println("Array before Sorting: "+Arrays.toString(arr));
selectionSort(arr);
System.out.println("After Sorting: ");
for (int i = 0; i < arr.length; i++) {
System.out.printf("[%d] = %d \n",i,arr[i]);
}
}

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++){
SWE-203L: Data Structures and Algorithms SSUET/QR/114

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


index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
}
Output:

5. Write a program that takes 10 numbers as input in an array. Sort the elements of array by
using Bubble sort. Print each iteration of the sorting process.

Code:
import java.util.Arrays;
import java.util.Scanner;
public class Task{
public static void main(String[] args) {
int[] arr = new int[10];
Scanner sc = new Scanner(System.in);
for (int i = 0; i <arr.length; i++) {
System.out.print("Enter a number: ");
arr[i] = sc.nextInt();
}
bubbleSort(arr);
System.out.println("\nArray After Sort: "+Arrays.toString(arr));
SWE-203L: Data Structures and Algorithms SSUET/QR/114

}
public static void bubbleSort(int[] arr){
for(int i=arr.length-1; i>0; i--){
// ->>
for (int j=0; j<i; j++){
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
System.out.println(Arrays.toString(arr));
}
}
}}}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

6. Write a program that takes 10 random numbers in an array. Sort the elements of array by
using Merge sort. Print each iteration of the sorting process.

Code:
package Task;
import java.util.*;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

public class Task{


void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

/* Create temp arrays */


int L[] = new int[n1];
int R[] = new int[n2];

/Copy data to temp arrays/


for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];

/* Merge the temp arrays */

// Initial indexes of first and second subarrays


int i = 0, j = 0;

// Initial index of merged subarry array


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++;
}

/* Copy remaining elements of L[] if any


while (i < n1) {
arr[k] = L[i];
SWE-203L: Data Structures and Algorithms SSUET/QR/114

i++;
k++;
}

// Copy remaining elements of R[] if any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void sort(int arr[], int l, int r)
{
if (l < r) {
// Find the middle point
int m =l+ (r-l)/2;

// Sort first and second halves


sort(arr, l, m);
sort(arr, m + 1, r);

// Merge the sorted halves


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

public static void main(String args[])


{
int arr[] = { 66, 58, 12, 90, 61, -17 };

System.out.println("Given Array");
printArray(arr);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Prg ob = new Prg();


ob.sort(arr, 0, arr.length - 1);

System.out.println("\nSorted array");
printArray(arr);
}
}
Output
Given Array
66 58 12 90 61 -17

Sorted Array
-17 12 58 61 66 90

Home Task

1. Declare an array of size n to store account balances. Initialize with values 0 to 1000000
and sort Account No’s according to highest balance values by using Quick sort, For e.g.:
Account No. 3547 Balance 28000
Account No. 1245 Balance 12000

Code:
package Task;
import java.util.*;

public class Task{


public static void main(String[] args) {
int[] arr = {30000,200,50000,100000,260000};
quickSort(arr,0,arr.length-1);
for (int i = arr.length-1;i>=0; i--){
System.out.printf("Account No %d Balance: %d\n",i+1,arr[i]);
}

}
public static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
SWE-203L: Data Structures and Algorithms SSUET/QR/114

arr[j] = temp;
}

public static int partition(int[] arr, int low, int high){


int pivot = arr[high];
int i = (low - 1);

for(int j = low; j <= high - 1; j++)


{
if (arr[j] < pivot){
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return (i + 1);
}

public static void quickSort(int[] arr, int low, int high){


if (low < high){
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 06
Searching in a Linear Array

Object
To find an element in linear array using Linear Search and Binary Search

Lab Task
7. Declare an array of size 10 to store account balances. Initialize with values 0 to 1000000.
Check all array if any value is less than 10000. Show message:
Account No .. Low Balance
Account No .. Low Balance

Code:
package Task;
import java.util.*;

public class Task{


public static void main(String[] args) {
int[] arr = {30000,200,50000,100000,260000,250000,0,58888,80000,9522,700000};

int i;
for (i=0;i<arr.length;i++){
for (i=0;i<arr.length;i++){
if (arr[i]<10000){
System.out.println("Acount No "+(i+1)+" has low balance."+arr[i]);;
}
}
}
}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

8. Write a program to search in array using Array built-in class.

Code:
import java.util.Scanner;
public class lab6dsa {
public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
Scanner input = new Scanner(System.in);
System.out.print("Search for :");
int k = input.nextInt();
int[] a1= {10,20,30,50,70,90};
int key = k;
System.out.println(key+" at index: "+linearSearch(a1, key));
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Home Task
1. Write a function called occurrences that, given an array of numbers A, prints all the
distinct values in A each followed by its number of occurrences. For example, if A = (28,
1, 0, 1, 0, 3, 4, 0, 0, 3), the function should output the following five lines (here separated
by a semicolon) “28 1; 1 2; 0 4; 3 2; 4 1”.

import java.util.HashSet;
import java.util.Scanner;
public class lab6dsa {
public static void main(String[] args){
int arri[] = {28,1,0,1,0,3,4,0,0,3};
HashSet<Integer> al = new HashSet<Integer>();
for(int i=0;i<arri.length;i++){
arri.add(arri[i]);
}
System.out.println("arr "+arri);
int[] arr = null;
for(int set : arr){
int count = 0;
for(int j=0;j<a.length;j++){
if(set==arri[j]){
count++;
}
}
System.out.println(set+" occurs "+count+" times");
}
}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Code:
package lab1;
import java.util.Scanner; public class lab1{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Secret Word: ");
String word = input.nextLine().toLowerCase();
StringBuffer blank= new StringBuffer();
for(int i=0; i<word.length(); i++){
blank.append("_");
}
System.out.println(blank);
int wrongCount = 0, guessCount = 0;
do {
System.out.print("Guess a letter: ");
String letter = input.next();
int index = word.indexOf(letter);
if(index == -1) {
wrongCount++;
System.out.println(blank);
}
else{
blank.replace(index,index+1,letter);
if(word.indexOf(letter,index+1)!=-1){
int index2 = word.indexOf(letter, index+1);
blank.replace(index2,index2+1,letter);
}
System.out.println(blank);
guessCount++;
}
}
while(wrongCount<7 && word.equalsIgnoreCase(blank.toString())!=true);
if(word.equalsIgnoreCase(blank.toString())){
System.out.println("You Guessed the word in "+(guessCount)+" guesses");
}
else{
System.out.println("Game Over !");
}
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:

2. Write a program that read a names from the given file ”Names” and searches for a
specific initial letter in the last name and write a new file “NewNames” with those
searched names.

Code:
package lab1;
import java.util.Scanner;
import java.io.*;
public class lab1 {
public static void main(String[] args) {
try{
Scanner input = new Scanner(System.in);
System.out.print("Enter Initial to search name: ");
String x = input.next();
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
File f2 = new File("C:\\Users\\ivc13004adm\\OneDrive\\nextfile.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f2));
String s;
System.out.println("Searching for names with initial "+x+":");
while((s = br.readLine())!=null){
if(s.indexOf(x)==0){
System.out.println("-"+s);
}
}
br.close();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

bw.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
Output:

Notepad:

3. Write a program that print total numbers of words in a file.

Code:
package lab1;
import java.io.*;
public class lab1 {
public static void main(String[] args) {
try{
File f = new File("C:\\Users\\ivc13004adm\\OneDrive\\nextfile.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String s;
int count = 0;
while ((s = br.readLine())!=null){ String[] words = s.split(" ");
count = words.length;
}
br.close();
System.out.println("No of Words: "+count); }catch(Exception e){ e.printStackTrace();
}
}
}}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:

Notepad:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Lab # 7

Singly Linked List Implementation

Object
Implementing singly linked list and associated operations.

Lab Tasks:
1. Write a program that can store 10 records of students in a link list manner and apply the
following operations on it.
a. View the list
b. Insert the elements in different locations of linked list and view it.
c. Search any element from the linked list
d. Delete record again view the list after deletion

Source Code:
package lab7;
public class LinkedList
{
Node head = null;
// static inner class
static class Node {
int data;
// connect each
node to next node
Node next;
public Node(int
data) {
this.data = data;
next = null;
}
}
public void
insertbegining(int data)
{
Node n = new
Node(data);
n.next= head;
head = n;
}
public void
insertAtPosition(Node
prev, int data){
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Node n = new
Node(data);
Node temp;
temp = prev.next;

prev.next = n;
n.next = temp;
}
public void
insertend(int data){
Node n = new
Node(data);
Node temp =
head;
Node prev = null;
while(temp!=null)
{
prev = temp;
temp =
temp.next;
}
prev.next = n;
n.next = null;
}
public void
delete(int data){
Node temp,
prev=null;
temp =head;
while(temp!=null
&& temp.data!=data){
prev = temp;
temp =
temp.next;
}
prev.next =
temp.next;
}
public void
searchNode(int data) {
Node current =
head;
int i = 1;
boolean flag =
false;
//Checks whether
list is empty
SWE-203L: Data Structures and Algorithms SSUET/QR/114

if(head == null) {

System.out.println("Lis
t is empty");
}
else {
while(current !=
null) {
//Compares
node to be found with
each node present in
the list

if(current.data == data)
{
flag = true;
break;
}
i++;
current =
current.next;
}
}
if(flag)

System.out.println("Ele
ment is present in the
list at the position : " +
i);
else

System.out.println("Ele
ment is not present in
the list");
}
public void
printList() {
Node temp =
head;
while(temp!=null)
{

System.out.println(tem
p.data);
temp =
temp.next;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

}
public static void
main(String[] args) {
// write your code here
System.out.println("Re
cord of Students are:
");
LinkedList ll =
new LinkedList();
Node first = new
Node(78);
ll.head = first;
Node second =
new Node(54);
first.next =
second;
Node third = new
Node(87);
second.next =
third;
Node fourth =
new Node(91);
third.next =
fourth;
Node fifth = new
Node(68);
fourth.next = fifth;
Node sixth = new
Node(75);
fifth.next = sixth;
Node seventh =
new Node(80);
sixth.next =
seventh;
Node eighth =
new Node(61);
seventh.next =
eighth;
Node ninth = new
Node(52);
eighth.next =
ninth;
Node tenth = new
Node(89);
ninth.next = tenth;
ll.printList();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.println("\
nAfter Insertion");

ll.insertbegining(45);

ll.insertAtPosition(thir
d, 56);
ll.insertend(66);
ll.printList();

System.out.println("\
nSearching");
ll.searchNode(91);

System.out.println("\
nAfter Deletion");
ll.delete(52);
ll.printList();
}
}

Output:

Home Tasks:

1. Write a program
that reads the
name, age and
salary of 10 persons
and perform the
following operations
on it.
SWE-203L: Data Structures and Algorithms SSUET/QR/114

a. View the list


b. Insert the elements in different locations of linked list and view it.
c. Search any element from the linked list
d. Delete record again view the list after deletion.

Source Code:

import
lab7.LinkedList;

public class
Lab7_HTask1 {
Node head = null;
// static inner class
static class Node {
String data;
// connect each
node to next node
Node next;
public
Node(String data) {
this.data = data;
next = null;
}
}
public void
insertbegining(String
data){
Node n = new
Node(data);
n.next= head;
head = n;
}

public void
insertAtPosition(Node
prev, String data){
Node n = new
Node(data);
Node temp;
temp = prev.next;
prev.next = n;
n.next = temp;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

public void
insertend(String data){
Node n = new
Node(data);
Node temp =
head;
Node prev = null;
while(temp!=null)
{
prev = temp;
temp =
temp.next;
}
prev.next = n;
n.next = null;
}
public void
delete(String data){
Node temp,
prev=null;
temp =head;
while(temp!=null
&& temp.data!=data){
prev = temp;
temp =
temp.next;
}
prev.next =
temp.next;
}
public void
searchNode(String
data) {
Node current =
head;
int i = 1;
boolean flag =
false;
//Checks whether
list is empty
if(head == null) {

System.out.println("Lis
t is empty");
}
else {
SWE-203L: Data Structures and Algorithms SSUET/QR/114

while(current !=
null) {
//Compares
node to be found with
each node present in
the list

if(current.data == data)
{
flag = true;
break;
}
i++;
current =
current.next;
}
}

if(flag)

System.out.println("Ele
ment is present in the
list at the position : " +
i);
else

System.out.println("Ele
ment is not present in
the list");
}

public void
printList() {
Node temp =
head;
while(temp!=null)
{

System.out.println(tem
p.data);
temp =
temp.next;
}
}
public static void
main(String[] args) {
SWE-203L: Data Structures and Algorithms SSUET/QR/114

// write your code


here

System.out.println("Na
mes of 10 person: ");
Lab7_HTask1 ll =
new Lab7_HTask1();
Node first = new
Node("Hassan");
ll.head = first;
Node second =
new Node("Omer");
first.next =
second;
Node third = new
Node("Usama");
second.next =
third;
Node fourth =
new Node("Hasnain");
third.next =
fourth;
Node fifth = new
Node("Hannan");
fourth.next = fifth;
Node sixth = new
Node("Zohaib");
fifth.next = sixth;
Node seventh =
new Node("Khubaib");
sixth.next =
seventh;
Node eighth =
new Node("Ammar");
seventh.next =
eighth;
Node ninth = new
Node("Usman");
eighth.next =
ninth;
Node tenth = new
Node("Furqan");
ninth.next = tenth;
ll.printList();

System.out.println("\
nAfter Insertion");
SWE-203L: Data Structures and Algorithms SSUET/QR/114

ll.insertbegining("Muz
ammil");

ll.insertAtPosition(four
th, "Asad");
ll.insertend("Ali");
ll.printList();

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

ll.searchNode("Omer")
;

System.out.println("\
nAfter Deletion");
ll.delete("Asad");
ll.printList();
}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 08
Doubly Linked List implementation of the list ADT

Object
Implementing doubly linked list and associated operations.

Lab Task
1. Write a program that can insert the records of employees in a link list. The record includes
employees’ name, designation, department and company name.
a. The program should be able to insert the record as first, last and as middle node
in the list.
b. The program should be able to search any record.
Code:

package Lab8;

import
Lab7.LinkedList
;

class
DoublyLinkedLis
t {
class Link
{
String
name,
designation,
department,
company;
Link
previous;
Link
next;

public
Link(String n,
String des,
String dep,
String com ){

this.name = n;

this.designatio
n = des;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

this.department
= dep;

this.company =
com;
}
}

//Initially,
heade and tail
is set to null
Link head,
tail = null;

//add a
node to the
list
public void
addNode(String
n, String des,
String dep,
String com ) {
Link
newLink = new
Link(n, des,
dep, com);

//if
list is empty,
head and tail
points to
newNode
if(head
== null) {

head = tail =
newLink;

//head's
previous will
be null

head.previous =
null;

//tail's next
will be null

tail.next =
SWE-203L: Data Structures and Algorithms SSUET/QR/114

null;
}
else {

//add newNode
to the end of
list. tail-
>next set to
newNode

tail.next =
newLink;

//newNode-
>previous set
to tail

newLink.previou
s = tail;

//newNode
becomes new
tail

tail = newLink;

//tail's next
point to null

tail.next =
null;
}
}
public void
insertAt(int
index, String
n, String des,
String dep,
String com) {
int
counter = 0;
Link
newLink = new
Link(n, des,
dep, com);
Link
link = head;
if(head
== null){
SWE-203L: Data Structures and Algorithms SSUET/QR/114

head = newLink;

tail = newLink;

return;
}

while(counter<i
ndex-1){

link =
link.next;

counter++;
}
Link
temp =
link.next;

link.next =
newLink;

link.next.next
= temp;
}

public void
print() {
Link
current = head;
if(head
== null) {

System.out.prin
tln("Doubly
linked list is
empty");

return;
}
int i =
1;

while(current !
= null) {

//Print each
node and then
go to next.
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.prin
tln("\nEmployee
"+i+":");

System.out.prin
tln("Name:
"+current.name)
;

System.out.prin
tln("Designatio
n:
"+current.desig
nation);

System.out.prin
tln("Department
:
"+current.depar
tment);

System.out.prin
tln("Company:
"+current.compa
ny);

current =
current.next;
i+
+;
}
}
public void
search(String
name){
if(head
== null){

System.out.prin
tln("List is
empty.");

return;
}
int
counter = 0;
Link
link = head;
int pos
= -1;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

while(link !=
null && pos ==
-1){

if(name.equalsI
gnoreCase(link.
name)){

pos =
counter+1;

break;
}

link =
link.next;

counter++;
}

if(pos != -1){

System.out.prin
tln(name+"
Found at
position:
"+pos);
}else{

System.out.prin
tln("Item not
Found!");
}

public
static void
main(String[]
args){

DoublyLinkedLis
t dll = new
DoublyLinkedLis
t();

dll.addNode("Mo
hsin Khan
Lodhi", "Senior
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Developer","IT"
,"Oracle");

dll.addNode("Sa
lman Junaid",
"Web
Developer",
"Web
Designing",
"Facebook");

dll.addNode("Mu
hammad
Hammad","Admini
strator",
"Administration
", "Google");

dll.insertAt(1,
"Abrar Ali",
"Assurance
Testing","Testi
ng","Microsoft"
);

dll.print();

System.out.prin
tln("\
nSearching:");

dll.search("Moh
sin Khan
Lodhi");
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Home Task
1. Write a program which includes these 3 classes

a) Create a class DNode with all the methods defined above.


b) Create a class DoublyLL to implement all the given operations.
c) Write a Demo class to create
o Unsorted Linked List and
o Sorted linked list

DNode Class Code:


package Lab8.HomeTask;

public class DNode {


static class DoublyLinkedList {
//A node class for doubly linked list
class Link {
int item;
Link previous;
Link next;

public Link(int item) {


this.item = item;
}
}

//Initially, heade and tail is set to null


Link head, tail = null;

//add a node to the list


public void addNode(int data) {
//Create a new node
Link newLink = new Link(data);

//if list is empty, head and tail points to newNode


if (head == null) {
head = tail = newLink;
//head's previous will be null
head.previous = null;
//tail's next will be null
tail.next = null;
} else {
//add newNode to the end of list. tail->next set to
newNode
tail.next = newLink;
//newNode->previous set to tail
newLink.previous = tail;
//newNode becomes new tail
tail = newLink;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

//tail's next point to null


tail.next = null;
}
}

public void insertAt(int index, int data) {


int counter = 0;
Link newLink = new Link(data);
Link link = head;
if (head == null) {
head = newLink;
tail = newLink;
return;
}
while (counter < index - 1) {
link = link.next;
counter++;
}
Link temp = link.next;
link.next = newLink;
link.next.next = temp;
}

//print all the nodes of doubly linked list


public void print() {
//Node current will point to head
Link current = head;
if (head == null) {
System.out.println("Doubly linked list is empty");
return;
}
System.out.println("Nodes of doubly linked list: ");
while (current != null) {
//Print each node and then go to next.
System.out.print(current.item + " ");
current = current.next;
}
}

public void search(int data) {


if (head == null) {
System.out.println("List is empty.");
return;
}
int counter = 0;
Link link = head;
int pos = -1;
while (link != null && pos == -1) {
if (data == link.item) {
pos = counter + 1;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

break;
}
link = link.next;
counter++;
}
if (pos != -1) {
System.out.println(data + " Found at position: " +
pos);
} else {
System.out.println("Item not Found!");
}

}
}

DoublyLL Class
Code:
package Lab8.HomeTask;

public class DoublyLL {


public static void main(String[] args){
DNode.DoublyLinkedList dll = new DNode.DoublyLinkedList();
dll.addNode(3);
dll.addNode(4);
dll.print();
System.out.println("\nAfter insertiion:");
dll.insertAt(1,7);
dll.print();
System.out.println("\nSearch 7: ");
dll.search(7);
}
}

Demo Class Code:


package Lab8.HomeTask;

public class Demo {


public static void main(String[] args) {
DNode.DoublyLinkedList unSorted = new
DNode.DoublyLinkedList();
unSorted.addNode(6);
unSorted.addNode(3);
unSorted.addNode(1);
DNode.DoublyLinkedList sorted = new DNode.DoublyLinkedList();
sorted.addNode(1);
sorted.addNode(2);
sorted.addNode(3);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.println("Unsorted Linked List:");


unSorted.print();
System.out.println("\nSorted Linked List:");
sorted.print();
}
}

Output ( DoublyLL
Class):

Output ( Demo
Class):
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 09
Stack Implementation

Object
To implement Stack as Arrays and linked list.

Sample Program
#1
public class
StackAsLinkedLi
st {
StackNode
root;

static
class StackNode
{
int
data;

StackNode next;

StackNode(int
data) {
this.data =
data; }
}

public
boolean
isEmpty()
{
if
(root == null)
{

return true;
}
else

return false;
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

public void
push(int data)
{

StackNode
newNode = new
StackNode(data)
;

if
(root == null)
{

root = newNode;
}
else {

StackNode temp
= root;

root = newNode;

newNode.next =
temp;
}

System.out.prin
tln(data + "
pushed to
stack");
}

public int
pop()
{
int
popped =
Integer.MIN_VAL
UE;
if
(root == null)
{

System.out.prin
tln("Stack is
Empty");
}
else {

popped =
SWE-203L: Data Structures and Algorithms SSUET/QR/114

root.data;

root =
root.next;
}
return
popped;
}

public int
peek()
{
if
(root == null)
{

System.out.prin
tln("Stack is
empty");

return
Integer.MIN_VAL
UE;
}
else {

return
root.data;
}
}

// Driver
code
public
static void
main(String[]
args)
{

StackAsLinkedLi
st sll = new
StackAsLinkedLi
st();

sll.push(10);

sll.push(20);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

sll.push(30);

System.out.prin
tln(sll.pop()

+ " popped from


stack");

System.out.prin
tln("Top
element is " +
sll.peek());
}

Output:

LAB TASK

1. Write a program
to create Stack
that can take
input random
candies color (i.e.
yellow, green,
orange, red etc)
and stored in
order. The user
likes any one of
the colored candy
to eat so he takes
SWE-203L: Data Structures and Algorithms SSUET/QR/114

out all the


candies, one by
one, eats only the
chosen color and
keeps other in
order so that he
can return them to
stack in exactly
the same order as
before minus the
chosen candies.
Print both the
input and
resultant stack.
For example:

Original
stack: Yellow-
>green->orange-
>yellow->red
Updated
stack: Green-
>orange->red i.e.
yellow is removed

Code:
package Lab9;

import java.util.Scanner;
public class CandiesStack {
StackNode root;

class StackNode{
String data;
StackNode next;

StackNode(String data){
this.data = data;
}
}

boolean isEmpty(){
if(root == null)
return true;
else
SWE-203L: Data Structures and Algorithms SSUET/QR/114

return false;
}
void push(String data){
StackNode newNode = new StackNode(data);
if (root == null){
root = newNode;
}else{
StackNode temp = root;
root = newNode;
root. next = temp;
}
}
String pop(){
if(root == null){
System.out.println("Stack Underflow !");
return "";
}else{
StackNode popped = root;
root = root.next;
return popped.data;
}
}

String candiePop(String candy){


if(root == null){
System.out.println("Sorry, The Stack is Empty!");
return "";
}else{
StackNode popNode = root;

while (popNode != null){

if(candy.equalsIgnoreCase(root.data)){
System.out.println("Here's your "+candy+" candy");
root = root.next;
return candy;

}else if(popNode.next !=null &&


candy.equalsIgnoreCase(popNode.next.data)){
System.out.println("Here's your "+candy+" candy");
popNode.next = popNode.next.next;
return candy;
}
popNode = popNode.next;
}
}
System.out.println("Candy not found!");
return "";
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

void display(){
if(root ==null){
System.out.println("The stack is empty!");
}else{
System.out.println("Stack contains: ");
StackNode counter = root;
while(counter != null){
System.out.println("-"+counter.data);
counter = counter.next;
}
System.out.println();
}
}

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
CandiesStack stack = new CandiesStack();
stack.push("red");
stack.push("green");
stack.push("blue");
stack.push("orange");
stack.display();
System.out.print("Enter candy to pop: ");
String candy = input.next();
stack.candiePop(candy);
System.out.println();
stack.display();

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

HOME TASK

1. Write a program to convert Infix expression into postfix expression by stack using linked list.

A + ( B * C - ( D / E | F ) * G ) * H

Code:
package Lab9;
import
java.util.Stack
;

public class
HomeTask {

public
static void
main(String[]
args){
String
exp = "A+(B*C-
(D/E+F)*G)*H";

System.out.prin
SWE-203L: Data Structures and Algorithms SSUET/QR/114

tln("Infix
notation:
"+exp);

System.out.prin
tln(infixToPost
fix(exp));
}
static int
Prec(char ch){

switch (ch)
{

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '^':

return 3;
}

return -1;
}

static
String
infixToPostfix(
String exp)
{

String result =
new String("");

Stack<Character
> stack = new
Stack<>();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

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

char c =
exp.charAt(i);

if
(Character.isLe
tterOrDigit(c))

result += c;

else if (c ==
'(')

stack.push(c);

else if (c ==
')')

while (!
stack.isEmpty()
&&

stack.peek() !=
'(')

result +=
stack.pop();

stack.pop();

else // an
operator is
encountered

while (!
SWE-203L: Data Structures and Algorithms SSUET/QR/114

stack.isEmpty()
&& Prec(c)

<=
Prec(stack.peek
())){

result +=
stack.pop();

stack.push(c);

//
pop all the
operators from
the stack

while (!
stack.isEmpty()
){

if(stack.peek()
== '(')

return "Invalid
Expression";

result +=
stack.pop();
}

return result;
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 10
Stack ADT Implementation
Object

Implement Stack by using Stack class.

Sample Program#1
Code:
package Lab10;
import
java.util.*;

public class
StackDemo {
static void
showpush(Stack
st, int a) {

st.push(new
Integer(a));

System.out.prin
tln("push(" + a
+ ")");

System.out.prin
SWE-203L: Data Structures and Algorithms SSUET/QR/114

tln("stack: " +
st);
}

static void
showpop(Stack
st) {

System.out.prin
t("pop -> ");
Integer
a = (Integer)
st.pop();

System.out.prin
tln(a);

System.out.prin
tln("stack: " +
st);
}

public
static void
main(String
args[]) {
Stack
st = new
Stack();

System.out.prin
tln("stack: " +
st);

showpush(st,
42);

showpush(st,
66);

showpush(st,
99);

showpop(st);

showpop(st);

showpop(st);

try {
SWE-203L: Data Structures and Algorithms SSUET/QR/114

showpop(st);
} catch
(EmptyStackExce
ption e) {

System.out.prin
tln("empty
stack");
}
}

}
Output:

Lab Task

1. Convert and evaluate the expression from infix to postfix using Stack ADT class.

(A+B) * (C-D)

Code:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

package Lab10;
import java.util.Stack;

public class Task1 {


public static void main(String[] args){
String exp = "(A+B)*(C-D)";
System.out.println("Infix notation: "+exp);
System.out.println("Postfix Notation: "+infixToPostfix(exp));
}
static int Prec(char ch){
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

static String infixToPostfix(String exp)


{
String result = new String("");

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

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


{
char c = exp.charAt(i);

if (Character.isLetterOrDigit(c))
result += c;

else if (c == '(')
stack.push(c);

else if (c == ')')
{
while (!stack.isEmpty() &&
stack.peek() != '(')
result += stack.pop();

stack.pop();
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

else // an operator is encountered


{
while (!stack.isEmpty() && Prec(c)
<= Prec(stack.peek())){

result += stack.pop();
}
stack.push(c);
}

// pop all the operators from the stack


while (!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
return result;
}
}

Output:

Home Task
1. Convert and evaluate the expression from infix to postfix using Stack ADT class.

A + ( B * C - ( D / E | F ) * G ) * H

Code:
package Lab10;
import java.util.*;

public class HomeTask{


public static void main(String[] args){
try{
String exp = "A+(B*C-(D/E+F)*G)*H";
String postfix = infixToPostfix(exp);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.println("Infix notation: "+exp);


System.out.println("Posfix notation: "+postfix);
postfix = postfix.replace("A","1");
postfix = postfix.replace("B","7");
postfix = postfix.replace("C","5");
postfix = postfix.replace("D","2");
postfix = postfix.replace("E","3");
postfix = postfix.replace("F","4");
postfix = postfix.replace("G","6");
postfix = postfix.replace("H","7");
System.out.println(postfix);
System.out.println("Evaluation:
"+evaluatePostfix(postfix));
}catch (EmptyStackException e){
e.printStackTrace();
}

static int evaluatePostfix(String exp) throws EmptyStackException{


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

// Scan all characters one by one


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 '*':
SWE-203L: Data Structures and Algorithms SSUET/QR/114

stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
static int Prec(char ch){
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

static String infixToPostfix(String exp) throws


EmptyStackException{
String result = new String("");

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

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


{
char c = exp.charAt(i);

if (Character.isLetterOrDigit(c))
result += c;

else if (c == '(')
stack.push(c);

else if (c == ')')
{
while (!stack.isEmpty() &&
stack.peek() != '(')
result += stack.pop();

stack.pop();
}
else // an operator is encountered
{
SWE-203L: Data Structures and Algorithms SSUET/QR/114

while (!stack.isEmpty() && Prec(c)


<= Prec(stack.peek())){

result += stack.pop();
}
stack.push(c);
}

// pop all the operators from the stack


while (!stack.isEmpty()){
if(stack.peek() == '(')
return "Invalid Expression";
result += stack.pop();
}
return result;
}
}

Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 11 Queues
Implementation
Object:
FIFO queue implementation using double end. Sample

Program 1:
Code:
package Lab11;

public class
QueueLinkedList {
class Node{ int data; Node next;
Node(int key){ this.data = key;
this.next=null;
}
}
Node front, rear; public QueueLinkedList() {
this.front = null; this.rear = null;
}
void enqueue(int key) { Node temp = new Node(key); if
(this.rear == null) { this.front = this.rear = temp; return;
}
this.rear.next = temp; this.rear = temp;
}
Node dequeue() { if (this.front == null) return
null; Node temp = this.front; this.front =
this.front.next; if (this.front == null) this.rear = null;
return temp;
}
public static void printList(QueueLinkedList list) { Node currentNode = list.front;
System.out.print("Linked List Elements: "); while (currentNode != null)
{System.out.print(currentNode.data + " "); currentNode = currentNode.next;
}
System.out.println();
}
public static void main(String[] args) { QueueLinkedList q = new QueueLinkedList();
q.enqueue(1);
q.enqueue(2);
q.enqueue(3); printList(q);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.println("D
equeued item is " +
q.dequeue().data); printList(q);
}}

Output:

Lab Tasks:
1. Write a program
to implement queue
using double end.

Code:
package Lab11;

public class QueueArray { private static int front, rear, capacity; private
static int queue[];

QueueArray(int c)
{
front = rear = 0; capacity = c;
queue = new int[capacity];
}

// function to insert an element


// at the rear of the queue static void queueEnqueue(int data)
{
// check queue is full or not if (capacity == rear) {
System.out.printf("\nQueue is full\n");
}

// insert element at the rear else { queue[rear] =


data; rear++;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

}
}

// function to delete an element // from the front of the queue


static void queueDequeue()
{
// if queue is empty if (front == rear) {
System.out.printf("\nQueue is empty\n");
}

// shift all the elements from index 2 till rear


// to the right by one else { for (int i = 0; i < rear - 1; i++) {
queue[i] = queue[i + 1];
}

// store 0 at rear indicating there's no element if (rear < capacity) queue[rear]


= 0;

// decrement rear rear--;


}
}

// print queue elements static void queueDisplay()


{ int i;
if (front == rear) {
System.out.printf("\nQueue is Empty\n"); return;
}

// traverse front to rear and print elements for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
}
}

// print front of queue static void queueFront()


{
if (front == rear) {
System.out.printf("\nQueue is Empty\n"); return;
}
System.out.printf("\nFront Element is: %d", queue[front]);
}
} class StaticQueueinjava {

// Driver code public static void main(String[] args)


{
// Create a queue of capacity 4
SWE-203L: Data Structures and Algorithms SSUET/QR/114

QueueArray q = new QueueArray(4);

// print Queue elements


QueueArray.queueDisplay();

// inserting elements in the queue


QueueArray.queueEnqueue(20);
QueueArray.queueEnqueue(30);
QueueArray.queueEnqueue(40);
QueueArray.queueEnqueue(50);

// print Queue elements


QueueArray.queueDisplay();

// insert element in the queue


QueueArray.queueEnqueue(60);

// print Queue elements


QueueArray.queueDisplay();

QueueArray.queueDequeue(); QueueArray.queueDequeue();

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

// print Queue elements


QueueArray.queueDisplay();

}
}
Output:
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Home Tasks:
1. Write a program that processes a group of input lines. Each input line contains an 'A' for
arrival or a 'D' for departure, and a license plate number. Cars are assumed to arrive and
depart in the order specified by the input. The program should: a) Print a message whenever
a car arrives or departs

b) When a car arrives, the message should specify whether or not there is a room
for the car in the garage. If there is no room, the car leaves without entering the garage.

c) When a car departs, the message should include the number of times that the
car was moved out of the garage to allow other cars to depart.
Code:
package Lab11;

public class lab11 { static class QueueArray { private static int front, rear,
capacity; private static int queue[];

QueueArray(int c)
{ front = rear = 0; capacity = c;
queue = new int[capacity];
}

// function to insert an element // at the rear of the queue


static void queueEnqueue(int data)
{
System.out.println("Car Arrived..");
// check queue is full or not if (capacity == rear) {
System.out.printf("\nNo room for more cars.\n");
}

// insert element at the rear else { queue[rear]


= data; rear++;
}
}

// function to delete an element // from the front of the queue


static void queueDequeue()
{
// if queue is empty if (front == rear) {

System.out.printf("\
nThere are no cars.
Empty Queue\n");
return;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

// shift all the elements from index 2 till rear


// to the right by one else {
System.out.println("Car Departured.."); int i; for (i = 0; i < rear
- 1; i++) { queue[i] = queue[i + 1];
}
System.out.println("The car moved "+(i+1)+" times.");

// store 0 at rear indicating there's no element if (rear < capacity)


queue[rear] = 0;

// decrement rear
rear--;
}
}

// print queue elements static void queueDisplay()


{ int i;
if (front == rear) {
System.out.printf("\nGarage is Empty\n"); return;
}

// traverse front to rear and print elements for (i = front; i < rear; i++) {
System.out.printf(" %d <-- ", queue[i]);
}
System.out.println();
}

// print front of queue static void queueFront()


{
if (front == rear) {
System.out.printf("\nQueue is Empty\n"); return;
}
System.out.printf("\nFront Element is: %d", queue[front]);
}
}
public static void main(String[] args){
QueueArray garage = new QueueArray(4);
QueueArray.queueEnqueue(123); QueueArray.queueDisplay();
QueueArray.queueEnqueue(456);
QueueArray.queueEnqueue(789);
QueueArray.queueEnqueue(101); QueueArray.queueDisplay();
QueueArray.queueEnqueue(102);
QueueArray.queueDisplay();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

QueueArray.queueDequeue();
QueueArray.queueDisplay();
QueueArray.queueDequeue();
QueueArray.queueDisplay();
QueueArray.queueDequeue(); QueueArray.queueDisplay();
QueueArray.queueDequeue();
QueueArray.queueDisplay();
QueueArray.queueDequeue();

}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 12
Implementation of Binary Search Tree

OBJECT:
Algorithm to implement binary search tree.

Sample Program:
Code:
package Lab12;
public class BinarySearchTree {
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
//Assign data to the new node, set left and right children to null
this.data = data;
this.left = null;
this.right = null; } }
//Represent the root of binary tree
public Node root;
public BinarySearchTree(){
root = null; }
void insert(int key) {
root = insert_Recursive(root, key);
} //insert() will add new node to the binary search tree
Node insert_Recursive(Node root, int key) {
//tree is empty
if (root == null) {
root = new Node(key);
return root; }
//traverse the tree
if (key < root.data) //insert in the left subtree
root.left = insert_Recursive(root.left, key);
else if (key > root.data) //insert in the right subtree
root.right = insert_Recursive(root.right, key);
// return pointer
SWE-203L: Data Structures and Algorithms SSUET/QR/114

return root; }
SWE-203L: Data Structures and Algorithms SSUET/QR/114

//minNode() will find out the minimum node


public Node minNode(Node root)
{ if (root.left != null)
return minNode(root.left);
else
return root; }
//deleteNode() will delete the given node from the binary search
tree
public Node deleteNode(Node node, int value) {
if(node == null){
return null; }
else {
//value is less than node's data then, search the value in left
subtree
if(value < node.data)
node.left = deleteNode(node.left, value);
//value is greater than node's data then, search the value in
right subtree
else if(value > node.data)
node.right = deleteNode(node.right, value);
//If //If value is equal to node's data that is, we have found the
node to be deleted
else {
//If node to be deleted has no child then, set the node to
null if(node.left == null && node.right == null)
node = null;
//If node to be deleted has only one right child
else if(node.left == null) {
node = node.right; }
//If node to be deleted has only one left child
else if(node.right == null) {
node = node.left; }
//If node to be deleted has two children node
else {
//then find the minimum node from right subtree
Node temp = minNode(node.right);
//Exchange the data between node and temp
node.data = temp.data;
//Delete the node duplicate node from right subtree
node.right = deleteNode(node.right,temp.data);
} }
return node;
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Lab # 13
Graph And Graph Traversal Objects Objective:
Implementing graph using BFS and DFS Sample

Program:
Code:
package Lab13;

import java.util.*; import


java.io.*;

public class Graph {


private int
V; // No. of
vertices
private
LinkedList<Inte
ger> adj[];
//Adjacency
Lists
//
Constructor
Graph(int v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}
// Function to add an edge into the graph
void addEdge(int v,int w)
{
adj[v].add(w);
}
// prints BFS traversal from a given source s
void BFS(int s)
{
// Mark all the
vertices as not
visited(By
default
SWE-203L: Data Structures and Algorithms SSUET/QR/114

// set as
false)
boolean visited[] = new boolean[V];
// Create a
queue for BFS

LinkedList<Inte
ger> queue =
new
LinkedList<Inte
ger>();
// Mark the current node as visited and enqueue
it visited[s]=true; queue.add(s);
while (queue.size() != 0)
{
// Dequeue a vertex from queue and print it
s = queue.poll();
System.out.print(s+" ");
// Get all
adjacent
vertices of the
dequeued vertex
s
// If a
adjacent has
not been
visited, then
mark it
// visited and
enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
// Driver
method to
SWE-203L: Data Structures and Algorithms SSUET/QR/114

public static void main(String args[]) {


Graph g = new Graph(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.prin
tln(" Breadth
First Traversal
" +
"(starting from
vertex 2)");
g.BFS(2);

} }

Output:

Lab Task:
1. Implement
BFS and DFS on
the given graph.
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Code:
package Lab13;

import
java.util.*;

public class GraphLab {


static class DepthGraph {
private
int V; // No.
of vertices

// Array of lists for //


Adjacency List Representation
private LinkedList<Integer> adj[];

//
Constructor

@SuppressWarnin
gs("unchecked")

DepthGraph(int
v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

// Function to add an edge into the graph


void addEdge(int v, int w)
{ adj[v].add(w); // Add w
to v's list.
}

// A
function used
by DFS
void DFSUtil(int v, boolean visited[])
{
//
Mark the
SWE-203L: Data Structures and Algorithms SSUET/QR/114

current node
as visited and
print it
visited[v] =
true;
System.out.prin
t(v + " ");

//
Recur for all
the vertices
adjacent to
this
//
vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) { int n = i.next();
if (!visited[n]) DFSUtil(n,
visited);
}
}

// The
function to do
DFS traversal.
It uses
recursive
// DFSUtil()
void DFS()
{
//
Mark all the
vertices as not
visited(set as
// false by default in java)
boolean visited[] = new boolean[V];

// Call the recursive helper function to print


DFS // traversal starting from all vertices one
by one for (int i = 0; i < V; ++i)
if (visited[i] == false) DFSUtil(i,
visited);
}

}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

static class BreadthGraph{


private int V; // No. of vertices
private
LinkedList<Inte
ger> adj[];
//Adjacency
Lists

//
Constructor

BreadthGraph(in
t v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
}

// Function to add an edge into the graph


void addEdge(int v,int w)
{
adj[v].add(w);
}

// prints BFS traversal from a given source s


void BFS(int s)
{
//
Mark all the
vertices as not
visited(By
default
//
set as false)
boolean visited[] = new boolean[V];

//
Create a queue
for BFS

LinkedList<Inte
ger> queue =
new
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LinkedList<Inte
ger>();
// Mark the current node as visited and enqueue
it visited[s]=true; queue.add(s);

while (queue.size() != 0)
{

// Dequeue a
vertex from
queue and print
it
s = queue.poll();
System.out.print(s+" ");

// Get all
adjacent
vertices of the
dequeued vertex
s

// If a
adjacent has
not been
visited, then
mark it

// visited and
enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
}
SWE-203L: Data Structures and Algorithms SSUET/QR/114

// Driver
method to
public static void main(String args[])
{
// For
BFS

BreadthGraph g
= new
BreadthGraph(5)
;

g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 0);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 1);
g.addEdge(2, 4);
g.addEdge(3, 0);
g.addEdge(4, 2);

System.out.prin
tln("Following
is Breadth
First Traversal
");

g.BFS(2);
// For
DFS

DepthGraph g2 =
new
DepthGraph(5);

g2.addEdge(0, 1);
g2.addEdge(0, 2); g2.addEdge(0,
3); g2.addEdge(1, 0);
g2.addEdge(1, 2); g2.addEdge(2,
0); g2.addEdge(2, 1);
g2.addEdge(2, 4); g2.addEdge(3,
0); g2.addEdge(4, 2);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.prin
tln("\
nFollowing is
Depth First
Traversal");

g2.DFS();
} }

Output:

Home Task:

1. Implement
BFS and DFS on
the below given
graph.

Code:
package Lab13; import
java.util.*; import
java.io.*;

public class HomeTask {


static class DepthGraph{
SWE-203L: Data Structures and Algorithms SSUET/QR/114

private
int V; // No.
of vertices

// Array of lists for //


Adjacency List Representation
private LinkedList<Integer> adj[];

//
Constructor

@SuppressWarnin
gs("unchecked")
DepthGraph(int
v)
{
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}

// Function to add an edge into the graph


void addEdge(int v, int w)
{ adj[v].add(w); // Add w
to v's list.
}

// A
function used
by DFS
void DFSUtil(int v, boolean visited[])
{
//
Mark the
current node as
visited and
print it
visited[v] = true;
System.out.print(v + " "); // Recur
for all the vertices adjacent to this
//
vertex
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) { int n = i.next();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

if (!visited[n]) DFSUtil(n,
visited);
}
}

// The
function to do
DFS traversal.
It uses
recursive
// DFSUtil()
void DFS()
{
//
Mark all the
vertices as not
visited(set as
// false by default in java)
boolean visited[] = new boolean[V];

// Call the recursive helper function to print


DFS // traversal starting from all vertices one
by one for (int i = 0; i < V; ++i)
if (visited[i] == false) DFSUtil(i,
visited);
}
}
static class BreadthGraph{
private int V; // No. of vertices
private
LinkedList<Inte
ger> adj[];
//Adjacency
Lists

//
Constructor

BreadthGraph(in
t v)
{
V = v;
adj = new LinkedList[v];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList();
SWE-203L: Data Structures and Algorithms SSUET/QR/114

// Function to add an edge into the graph


void addEdge(int v,int w)
{
adj[v].add(w);
}

// prints BFS traversal from a given source s


void BFS(int s)
{
//
Mark all the
vertices as not
visited(By
default
// set as
false)
boolean visited[] = new boolean[V];

//
Create a queue
for BFS

LinkedList<Inte
ger> queue =
new
LinkedList<Inte
ger>();
// Mark the current node as visited and enqueue
it visited[s]=true; queue.add(s);

while (queue.size() != 0)
{

// Dequeue a
vertex from
queue and print
it
s = queue.poll();
System.out.print(s+" ");

// Get all
adjacent
vertices of the
SWE-203L: Data Structures and Algorithms SSUET/QR/114

dequeued vertex
s

// If a
adjacent has
not been
visited, then
mark it

// visited and
enqueue it
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
}
public static void main(String[] args) {

System.out.prin
tln("Breadth
First Traversal
:");
BreadthGraph g
= new
BreadthGraph(80
);
g.addEdge(40,20);
g.addEdge(40,10);
g.addEdge(20,10);
g.addEdge(20,30);
g.addEdge(10,30);
g.addEdge(30,60);
g.addEdge(50,70);
g.addEdge(60,70);

g.BFS(40);
SWE-203L: Data Structures and Algorithms SSUET/QR/114

System.out.prin
tln("\nDepth
First Traversal
:");
SWE-203L: Data Structures and Algorithms SSUET/QR/114

DepthGraph g2 = new DepthGraph(71);


g2.addEdge(40,20); g2.addEdge(40,10);
g2.addEdge(20,10); g2.addEdge(20,30);
g2.addEdge(10,30); g2.addEdge(30,60);
g2.addEdge(50,70); g2.addEdge(60,70);

g2.DFS();

} }

Output:

Name: Nabiha Mirza


Roll No: 2020-SE-166 Page 112
SWE-203L: Data Structures and Algorithms SSUET/QR/114

LAB # 14
Implementing Hashing techniques and using HashTable ADT and
Collision Resolution Techniques
Object
Implementing Hashing techniques with collision resolution
Sample Program:
Code:
package Lab14;
import java.util.*;
public class HT {
public static void main(String[] args) {
Hashtable<String, Integer> ht = new Hashtable<>();
ht.put("arif", 10);
ht.put("saleem", 30);
ht.put("wasif", 20);
System.out.println("Size of map is:- " + ht.size());
System.out.println(ht);
if (ht.containsKey("arif")) { Integer a = ht.get("arif");
System.out.println("value for key" + " \"arif\" is:- " +
a); } } }
Output:

Name: Nabiha Mirza


Roll No: 2020-SE-166 Page 113
SWE-203L: Data Structures and Algorithms SSUET/QR/114

Lab Task:
1. Write a class to maintain a hash function to implement a digit-folding approach in the hash
function. Your program should work for any array size and any key length. Use linear probing.

Code:
package Lab14;
import java.util.Scanner;

public class DigitFolder {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter size of Array to perform digit
folding:");
int size = input.nextInt();
System.out.print("Enter value to perform digit folding: ");
int val = input.nextInt();
int hashVal = hashFunc(val,size);
System.out.println("Hash value: "+hashVal);
}
public static int hashFunc(int key,int size) {
int arraySize = size;
int keyDigitCount = getDigitCount(key);
int groupSize = getDigitCount(arraySize);
int groupSum = 0;
String keyString = Integer.toString(key);
int i;
for (i = 0; i < keyString.length(); i += groupSize) {
if (i + groupSize <= keyString.length()) {
String group = keyString.substring(i, i +
groupSize);
groupSum += Integer.parseInt(group); } }
// There is no remaining part if count is divisible by groupsize.
if (keyDigitCount % groupSize != 0) {
String remainingPart =
keyString.substring(i - groupSize,
keyString.length());
groupSum += Integer.parseInt(remainingPart);
}
return groupSum % arraySize;
} public static int getDigitCount(int n) {
int numDigits = 1;
while (n > 9) {

Name: Nabiha Mirza


Roll No: 2020-SE-166 Page 114
SWE-203L: Data Structures and Algorithms SSUET/QR/114

n /= 10;
numDigits++;
}
return numDigits; } }
Output:

Home Task:
1. Enter data of a cricket team 11 players which is supposed to be a hash table value and insert runs
of each player as a data, find out key treat’s Rank# of a player.
For example: Runs are 30 mod by 11 which is index no 8; rank#8 is a rank of a team member. (Use
HashTable ADT class)

Code:
package Lab14;
import java.util.*;

public class HomeTask {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Hashtable<String, Integer> team = new Hashtable<>();
team.put("Nabiha", 99);
team.put("Sobia", 100);
team.put("Zainab", 98);
team.put("Seemal", 97);
team.put("Areesha", 96);
team.put("Zejah",95);
team.put("Mola Baksh", 94);
team.put("Ali", 93);
team.put("Salman", 92);
team.put("Abdul Rehman", 91);
team.put("Moiz", 90);

Name: Nabiha Mirza


Roll No: 2020-SE-166 Page 115
SWE-203L: Data Structures and Algorithms SSUET/QR/114

rankFinder(team); }
public static void rankFinder(Hashtable table) {
int counter = 0;
ArrayList<Integer> ranks = new ArrayList<>();
ArrayList<String> members = new ArrayList<>();
ArrayList<Integer> scores = new ArrayList<>();
Set<String> keys = table.keySet();
for (String key : keys) {
int rank = (int) table.get(key) % 11;
if (rank==0){
rank++; }
while (ranks.contains(rank)) {
rank++;
}
ranks.add(rank);
members.add(key);
scores.add((int)table.get(key));
counter++; }
Sort(ranks, members,scores);
for (int i=0; i<11; i++){
System.out.printf("%s - scores: %d - rank: %d\
n",members.get(i),scores.get(i),ranks.get(i)); } }
static void Sort(ArrayList<Integer> ranks, ArrayList<String>
members, ArrayList<Integer> scores) {
int n = ranks.size();
int n2 = n;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (ranks.get(j - 1) > ranks.get(j)) {
//swap rank
temp = ranks.get(j - 1);
ranks.set(j-1,ranks.get(j));
ranks.set(j, temp);
//swap members
String temp2 = members.get(j - 1);
members.set(j - 1, members.get(j));
members.set(j, temp2);

//swap scores
int temp3 = scores.get(j-1);

Name: Nabiha Mirza


Roll No: 2020-SE-166 Page 116
SWE-203L: Data Structures and Algorithms SSUET/QR/114

scores.set(j - 1, scores.get(j)); scores.set(j, temp3); } } } } }

Output:

Name: Nabiha Mirza


Roll No: 2020-SE-166 Page 117

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy