mishayy.files.wordpress.com  · web viewlecture #1. data structure . data: the word data is a...

76
Data Structures and Algorithm Semester: 3 rd Year: 2 nd LECTURE #1 Data structure Data : The word data is a plural noun so write " data are". Datum is the singular Facts and figures is called a data Data is nam given to basic facts or raw facts. For example: numbers of items sold by a business or numerical values used in some mathematical calculation When a data has been processed into a more useful or intelligible form ( e.g by a computer ) it is called information. Example : “Ahmed” , 48 is a data the examination result for Mr. Ahmed is 48% and a pass is information Structure : The arrangement of and relations between the parts or elements. Data structure Organization of data and the relationship among its members is called data structure. When individual items are arranged or organized together as one unit then we call such an organized called of data structure. Algorithm : It is a set of instructions which describes the steps to be filled to get the solution of a problem. Or It is a process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer. or An algorithm is a procedure or formula for solving a problem, based on conducting a sequence of specified actions. The word algorithm derives from the name of the mathematician, Mohammed ibn-Musa al-Khwarizmi, who was part of the royal court in Baghdad and who lived from about 780 to 850. Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language. By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 1 of 76

Upload: lelien

Post on 07-Jun-2019

214 views

Category:

Documents


0 download

TRANSCRIPT

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #1Data structure

Data: The word data is a plural noun so write "data are". Datum is the singularFacts and figures is called a dataData is nam given to basic facts or raw facts.For example: numbers of items sold by a business or numerical values used in some mathematical calculationWhen a data has been processed into a more useful or intelligible form ( e.g by a computer ) it is called information.

Example : “Ahmed” , 48 is a data the examination result for Mr. Ahmed is 48% and a pass is informationStructure : The arrangement of and relations between the parts or elements.

Data structureOrganization of data and the relationship among its members is called data structure.When individual items are arranged or organized together as one unit then we call such an organized called of data structure.

Algorithm : It is a set of instructions which describes the steps to be filled to get the solution of a problem. Or It is a process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer.orAn algorithm is a procedure or formula for solving a problem, based on conducting a sequence of specified actions. The word algorithm derives from the name of the mathematician, Mohammed ibn-Musa al-Khwarizmi, who was part of the royal court in Baghdad and who lived from about 780 to 850.

Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be implemented in more than one programming language.

Algorithm properties

An algorithm possess the following properties1. It must be correct2. It must be composed of a series of concrete( means they are real) steps.3. There can be no ambiguity as to which step will be performed next.4. It must be composed of a finite number of steps.5. It must terminate

Characteristics of an algorithm

Algorithm has the following Characteristics

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 1 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

1. Each and every instruction should be precise and unambiguous2. Each instruction should be such that it can be precise such that it can be performed in a finite

time.3. One or more instructions should not be repeated infinitely. This ensures that the algorithm will

ultimately terminate.4. After performing the instructions that is after the algorithm terminates, the desired results

must be obtained.

Characteristics of a Data Structure

Correctness − Data structure implementation should implement its interfacecorrectly.

Time Complexity − Running time or the execution time of operations of datastructure must be as small as possible.

Space Complexity − Memory usage of a data structure operation should be aslittle as possible.

Need for Data Structure

As applications are getting complex and data rich, there are three common problems that applications face now-a-days.Data Search − Consider an inventory of 1 million(106) items of a store. If theapplication is to search an item, it has to search an item in 1 million(106) itemsevery time slowing down the search. As data grows, search will become slower.Processor Speed − Processor speed although being very high, falls limited if thedata grows to billion records.Multiple Requests − As thousands of users can search data simultaneously on aweb server, even the fast server fails while searching the data.To solve the above-mentioned problems, data structures come to rescue. Data can be organized in a data structure in such a way that all items may not be required to be searched, and the required data can be searched almost instantly.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 2 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE # 2,3

Problem analysis & SpecificationWhen selecting a data structure to solve a problem, you should follow these steps. 1. Analyze your problem to determine the basic operations that must be supported. Examples of basic operations include inserting a data item into the data structure, deleting a data item from the data structure, and finding a specified data item. 2. Quantify the resource constraints for each operation. 3. Select the data structure that best meets these requirements.AnalysisTo analyze is generally the running time. Typically, the size of the input is the main consideration We define two functions, T avg(n) and T worst(n), as the average and worst-case running time, respectively, used by an algorithm on input of size n. Clearly, T avg(n) T worst(n). If there is more than one input, these functions may have.

Problem: A problem is a function or a mapping of inputs to outputs.Program: A program is an instantiation of an algorithm in a computer programming language.Example:Problem: find y = x to the power of 2Algorithm1: multiply x by xAlgorithm2: Add x to itself x itemsProgram: for(int I =0;i<=x;i++) y += x;

Data Structure selection and algorithm development How to Write an Algorithm?Algorithm writing is a process and is executed after the problem domain is well-defined. That is, we should know the problem domain, for which we are designing a solution Design an algorithm to add two numbers and display the result. step 1 – START step 2 − declare three integers a, b & c step 3 − define values of a & b step 4 − add values of a & b step 5 − store output of step 4 to c step 6 − print c step 7 – STOPcoding in java import java.util.Scanner; public class al1 { public static void main(String[] args) { int a,b,c; Scanner ob = new Scanner(System.in); System.out.print("Enetre the value of a "); a = ob.nextInt();

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 3 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

System.out.print("Enetre the value of b "); b = ob.nextInt(); System.out.println(a+" + "+b+" = "+(a+b)); } }Output Enetre the value of a 12 Enetre the value of b 312 + 3 = 15

Data type:Data Type Data type is a way to classify various types of data such as integer, string, etc. which determines the values that can be used with the corresponding type of data, the type of operations that can be performed on the corresponding type of data. There are two data types

Built-in Data Type Derived Data Type Built-in Data Type

Those data types for which a language has built-in support are known as Built-in Data types. For example, most of the languages provide the following built-in data types. Integers , Boolean (true, false), Floating (Decimal numbers), Character and StringsDerived Data Type Those data types which are implementation independent as they can be implemented in one or the other way are known as derived data types. These data types are normally built by the combination of primary or built-in data types and associated operations on them. For example − List, Array Stack, and Queue.

Classification of data structureData structure s are classified as either linear or non linear data structure.Linear data structure A data structure is said to be linear if its elements form a sequence.How many basic ways of representing linear data structure in computer memory?Solution There are two basic ways of representing such linear data structures in computer memory.

1. One way is to have the linear relationship between the elements represented by means of sequential computer memory location s. These linear data structures are called arrays.

2. The other ways is to have the linear relationship between the elements represented by means of pointers or links. These data structures are called linked lists.Types of linear data structures

The types of linear data structures are namely string arrays, linked lists, stacks and queues.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 4 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE # 4,5

Data Structures operations What type of operations one normally performs on any linear data structures ?Solution The operations one normally performs on any linear data structures include the following.

i. Traversal : processing each element in the list.ii. Insertion : adding a new element to the list..iii. Deletion: removing an element from the list.iv. Sorting : Arranging the elements in some type of order.v. Merging : combining two lists into a single list.

Nonlinear data structure

This data structure is mainly used to represent data containing a hierarchical relationship between elements . Example: records, family trees, and tables of contents.

ADT (abstract data type )An ADT is a data structure and collection of functions or procedures which operate on the data structure. Stacks and QUEUES can be considered examples of ADT ( abstract data types )

Data types: kind of values that can be solved and manipulated.Identifier: An identifier is a user defined word which consists of :Letters , Digits_ (underscore) $ (a dollar sign )Variables: variables are the name of the location that stores a value.

Construct an algorithm traverses DATA applying on operation PROCESS to each element of DATA. Algorithm

Traverse(data, n)Step1: Repeat for k=0 to n;Apply process to data[k][end of loop]Step2: Exit

Coding

import java.util.Scanner; class traverse { public static void traver(int[] data,int n){ Scanner ob = new Scanner(System.in);for(int i = 0;i<=n;i++) { System.out.print("data["+i+"]="); data[i]=ob.nextInt(); }} public static void main(String[] args) {

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 5 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

int[] data=new int[10]; int n; Scanner ob = new Scanner(System.in); System.out.print("Enter number of elements"); n = ob.nextInt(); traver(data,n); }}

Write an algorithm that insert an item into kth location of an array data.

Algorithm Insert(data,k,n,item)Step1: set j=n;Step2: Repeat steps 3 and 4 while j>=kStep3:move kth element downwarddata[j+1]=data[j]Step4: [decrease counter] j = j-1[end of step2]Step6: Insert element data[k]=itemStep7: Reset n=n+1;Step8: Exit

Coding import java.util.Scanner; public class TRA { public static void traver(int[] data,int n) {Scanner ob = new Scanner(System.in); for(int i = 0;i<=n;i++) {System.out.print("data["+i+"]="); data[i]=ob.nextInt(); } }public static void insert(int[] data,int n,int k,int item) {int j=n; while(j>=k) { data[j+1]= data[j]; j--; } data[k] =item; n++; }public static void main(String[] args) { int[] data=new int[10]; int n; Scanner ob = new Scanner(System.in); System.out.print("Enter number of elements"); n = ob.nextInt(); traver(data,n); System.out.print("Enter the location"); int l =ob.nextInt(); System.out.print("Enter the item"); int el = ob.nextInt(); insert(data,n,l,el); for(int i=0;i<=n+1;i++)

System.out.println("data["+i+"]="+data[i]); } }Out putEnter number of elements2data[0]=12data[1]=3

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 6 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

data[2]=4Enter the location1Enter the item8data[0]=12data[1]=8data[2]=3

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 7 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #6, 7

Develop a delt(data,n,k,item) that delete an element item from the kth position of an array data

Algorithm delete(data,n,k)Step1 set b=kStep2 Repeat 3 and 4 while(b<n)Step3 [move data upward] data[b]=data[b+1]Step4[increase counter] b=b+1[end of while loop]Step#5 n=n-1Step#6 Exit

Coding import java.util.Scanner; public class DELT { public static void traver(int[] data,int n) {

Scanner ob = new Scanner(System.in);for(int i = 0;i<=n;i++) {

System.out.print("data["+i+"]=");data[i]=ob.nextInt(); } }

public static void delt(int[] data,int n,int k,int item) { item = data[k]; for(int j= k;j<=n-1;j++)

data[j]=data[j+1]; n--; } public static void main(String[] args) { int[] data=new int[10]; int n; Scanner ob = new Scanner(System.in); System.out.print("Enter number of elements"); n = ob.nextInt(); traver(data,n); System.out.println("\n"); System.out.print("Enter the location"); int l =ob.nextInt(); System.out.print("Enter the item"); int el = ob.nextInt(); delt(data,n,l,el); System.out.println("\n"); for(int i=0;i<=n-1;i++) System.out.println("data["+i+"]="+data[i]); System.out.println("\n\ndeleted item "+el+"\tfrom location\t"+l); } }Enter number of elements2data[0]=12data[1]=3data[2]=4Enter the location1Enter the item3data[0]=12

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 8 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

data[1]=4deleted item 3 from location 1

Write an algorithm that sort an elements in DATA using bubble sort technique.

Algorithm bubbleSort(a,n)Step1 Repeat for i=0 to n-1Step2 set b=0Step3 Repeat 4 and 5 while(b<n-1)Step4 if(a[b]>a[b+1])[Swap the values of a[b] and a[b+1]]Step5 increment b=b+1[end of while][end of outer loop]Step#6 Exit.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 9 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #8, 9

Write an algorithm that sorting the number of elements from an array DATA using selection sort technique.

Algorithm:

Selection (d,n)Step1: repeat 2 to 5 for i=0 to n-1Step2: Smallest=I;Step3: repeat for k=i+1 to nStep4: if d[smallest]>data[k] thenSmallest = [end of if][end of inner loop]Step5: if( i != smallest) then[interchange]d[i] and d[smallest][end of if][end of outer loop]Step6: Exit

Coding:

import java.util.Scanner; public class selection1 { public static void traver(int[] data,int n)

{ Scanner ob = new Scanner(System.in);for(int i = 0;i<=n;i++) { System.out.print("data["+i+"]=");

data[i]=ob.nextInt(); } }public static void select(int[] data,int n) { for(int i=0;i<=n-1;i++){ int s= i; for(int k = i+1;k<=n;k++) { if(data[s]>data[k]) s=k; }

if(i!=s) { int temp = data[i];data[i]= data[s]; data[s]=temp; }}}

public static void main(String[] args) { int[] data=new int[10]; int n,temp; Scanner ob = new Scanner(System.in); System.out.print("Enter number of elements"); n = ob.nextInt(); traver(data,n); select(data,n); System.out.println("\n"); for(int i=0;i<=n;i++)System.out.println("data["+i+"]="+data[i]); }}

Write an algorithm that sort elements using insertion sort technique.Algorithm Insert(data,n)

1. data[0]=0{ initialize sentinel element }2. repeat steps 3 to 5 for k = 2 to n3. temp = data[k] and ptr = k-1

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 10 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

4. repeat while temp<data[ptr](a) set data[ptr+1]= data[ptr] { move elements forward }(b) set ptr = ptr-1

[ end of loop ]5. set data[ptr+1] = temp {insert element in proper place }

[ end of step 2 loop ]6. return

coding:

import java.util.Scanner; public class INSERTION {public static void traver(int[] data,int n) {Scanner ob = new Scanner(System.in); for(int i = 1;i<=n;i++){System.out.print("data["+i+"]=");data[i]=ob.nextInt(); } }public static void insert(int[] data,int n){ int temp,p; data[0]=0; for(int k=2;k<=n ;k++) {temp=data[k]; p = k-1; while(temp<data[p]) {data[p+1]= data[p]; p--; } data[p+1]=temp; } }public static void main(String[] args) { int[] data=new int[10]; int n,temp; Scanner ob = new Scanner(System.in); System.out.print("Enter number of elements"); n = ob.nextInt(); traver(data,n); insert(data,n); System.out.println("After sorting \n");

for(int i=1;i<=n;i++) System.out.println("data["+i+"]="+data[i]); } }

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 11 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #10

Radix sortRadix Sort is an algorithm that sorts a list of numbers and comes under the category of distribution sort.This sorting algorithm doesn't compare the numbers but distributes them, it works as follows:1. Sorting takes place by distributing the list of number into a bucket by passing through the individual digits of a given number one-by-one beginning with the least significant part. Here, the number of buckets are a total of ten, which bare key values starting from 0 to 9.2. After each pass, the numbers are collected from the buckets, keeping the numbers in order3. Now, recursively redistribute the numbers as in the above step '1' but with a following reconsideration: take into account next most significant part of the number, which is then followed by above step '2'.Radix Sort Java Algorithm1. Find the length of the number that has maximum number of digits.2. Initialize i=0, Repeat the below procedure till the length equals i.3. Fill the bucket with all the digits in ith position.4. Sort out the digits according to the order.5. If length=i, i=i*10, goto to step 3. Else go to step 56. Print the sorted array.7. EndRadix Sort Java Codingimportjava.util.Scanner; classRadixSort { static void sort( int[] a) { int i, m = a[0], exp = 1, n = a.length; int[] b = new int[10]; for (i = 1; i < n; i++) if (a[i] > m) m = a[i]; while (m / exp> 0) { int[] bucket = new int[10]; for (i = 0; i < n; i++) bucket[(a[i] / exp) % 10]++; for (i = 1; i < 10; i++) bucket[i] += bucket[i - 1]; for (i = n - 1; i >= 0; i--) b[--bucket[(a[i] / exp) % 10]] = a[i]; for (i = 0; i < n; i++) a[i] = b[i]; exp *= 10; } } public static void main(String[] args) { Scanner scan = new Scanner( System.in ); System.out.println("Radix Sort Testn"); int n, i; System.out.println("Enter number of integer elements"); n = scan.nextInt(); intarr[] = new int[ n ]; System.out.println("\nEnter "+ n +" integer elements"); for (i = 0; i < n; i++) arr[i] = scan.nextInt(); sort(arr); System.out.println("\nElements after sorting "); for (i = 0; i < n; i++) System.out.print(arr[i]+" "); System.out.println(); }}

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 12 of 61

Radix Sort TestEnter number of integer elements6Enter 6 integer elements12 9 15 4 0 1Elements after sorting 0 1 4 9 12 15

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #11,12

Complexity of an algorithm:

Complexity of an algorithm is the measurement of how efficient an algorithm is in terms of speed and space. It determines the required space for storage and processing time proportional to the number of input data elements given to an algorithm.In other words the complexity of an algorithm which is a numeric value give the running time and storage space requirement in terms of number of input data, denoted as c(n)=nConsider algorithm given below, which finds the location loc and the data value MAX of the largest elements in the array data.Algorithm(largest elements in the array)

1. k=1, loc =1 and max = data[1]2. Repeat steps 3 to 4 while(k ≤ n )3. K=k+14. If max<data[k] then loc = k and max = data[k]

[end of if structure ][ end of loop of step 2 while ]

5. Write: loc, max6. exit

Determine the complexity c(n) which is the number of processing / executions inside the step 4 condition when satisfied. For example if max and data[1] = 50 then the condition in step 4 (5<50) is true then complexity c(n) is increase by 1 and so on.Describe and find complexity for a) worst case (b) best case (c) Average case when n=4(a) Worst case The maximum value of c(n) for any possible input is called worst caseC(n) for the worst caseC(n) = n-1C(4) = 4-1C(4) = 3(b) best case C(n) for the best caseC(n) = nC(4) = 0 The minimum value of c(n) for any possible input is called best case

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 13 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

(c) C(n) for the average caseThe expected value of c(n) is called average caseSince n = 4There are 4! = 1*2*3*4= 24Possible permutationsHere 1 = largest element 4 = smallest elementPermutation p Processing np

12340

12340

12340

12340

12340

12340

Permutation p Processing np

21341

23141

24311

24131

23411

21431

Permutation p Processing np

31242

32142

34212

34122

32412

31422

Permutation p Processing np

41233

42133

43213

43123

42313

41323

Suppose 1 = 50 2 = 40 3 = 30 4 = 20C(n) = ∑np ------- = 0+6+12+18 N! ------------------ 2436---- = 3 / 2 24

C(n) = 3 / 2

Execution Time CasesThere are three cases which are usually used to compare various data structure's execution time in a relative manner.Worst Case − This is the scenario where a particular data structure operationtakes maximum time it can take. If an operation's worst case time is ƒ(n) thenthis operation will not take more than ƒ(n) time, where ƒ(n) represents functionof n.Average Case − This is the scenario depicting the average execution time of anoperation of a data structure. If an operation takes ƒ(n) time in execution, thenm operations will take mƒ(n) time.Best Case − This is the scenario depicting the least possible execution time of anoperation of a data structure. If an operation takes ƒ(n) time in execution, thenthe actual operation may take time as the random number which would bemaximum as ƒ(n).

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 14 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Basic TerminologyData − Data are values or set of values.Data Item − Data item refers to single unit of values.Group Items − Data items that are divided into sub items are called as GroupItems.Elementary Items − Data items that cannot be divided are called as ElementaryItems.Attribute and Entity − An entity is that which contains certain attributes orproperties, which may be assigned values.Entity Set − Entities of similar attributes form an entity set.Field − Field is a single elementary unit of information representing an attributeof an entity. Record − Record is a collection of field values of a given entity.File − File is a collection of records of the entities in a given entity set.

Space time trade off of an algorithm The space time trade off refers to a device between algorithm solution of a data processing problem that allows one to decrease the running time of an algorithm solution by increasing the space to store the data and vice versa.The expected running time of linear search algorithm is f(n) = n / 2 and for the binary search algorithm is f(n) = log2n Suppose a data set S contains n elements . Determine the running time of the linear search and binary search algorithm when n = 1000 and n = 10,000SolutionWhen N = 1000Linear search algorithm’s running time is given belowT1 = n/2 = 1000 / 2 = 500Binary search algorithm’s running time is given belowT2= log2 n = log21000Log2(210) ~ 10Linear search algorithm’s running time is given belowT1 = n / 2 , 10000/2 = 5000Binary search algorithm’s running time is given belowT2= log2 n = log210000Log2(213) ~ 13

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 15 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #13, 14

Develop an algorithm that performs operation call by value. Algorithm for call by value Step1: start. Step2: declare a class known as byvalue. Step3: intialize and declare the integer variable data with value 50. Step4: declare a function change with integer variable data. Step5: calculate data=data+100. Step6: declare a main function inside the class byvalue. Step7: create an object op in class byvalue. Step8: display the value of data before change. Step9: make a function call to change() using operator op. Step10: display the value of data after change. Step11: stop. Coding Source code for call by value: class byvalue { int data=50; void change(int data) { data=data+100; //changes will be in the local variable only } public static void main(String args[]) { byvalue op=new byvalue(); System.out.println("before change "+op.data); op.change(500); System.out.println("after change "+op.data); } } Develop an algorithm that performs operation call by reference Algorithm Algorithm for call by reference: Step1: start Step2: declare a class known as operation2. Step3: intialize and declare variable data with value 50. Step4: declare a function change with an object op of class operation2. Step5: calculate the value of data=data+100 using object op. Step6: declare a main function in class operation2. Step7: create an object op in class operation2. Step8: display the value of data before change. Step9: make a function call to change() using operator op. Step10: display the value of data after change.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 16 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Step11: stop.

Source code for call by reference: class Operation2 { int data=50; void change(Operation2 op) { op.data=op.data+100;//changes will be in the instance variable } public static void main(String args[]) { Operation2 op=new Operation2(); System.out.println("before change "+op.data); op.change(op);//passing object System.out.println("after change "+op.data); } }

Matrices/Multidimensional arrays: combination of tables is called matrices. In other words the combination of rows and columns. Let A be an M*P matrix array, and let B be a P*N matrix array. develop an algorithm stores the product of A and B in an M*N matrix array CMATMUL(A , B , C , M , P , N)

1. Repeats steps 2 to 4 for I = 1 to M2. Repeats steps 3 and 4 for J = 1 to N3. Set C[ I , J ] = 0 { initializes C[ I , J ] } 4. Repeat for k = 1 to P

C[ I , J ] = C[ I , J ] + A[I , K ] * B[ K , J ][End of inner loop ][End of step 2 middle loop ] [End of step 1 outer loop ]

5.ExitWrite a program that stores the product of A and B in M*N matrix array C import java.util.Scanner; public class mult {

public static void multi(int a[][],int b[][],int c[][]) { Scanner obj = new Scanner (System.in); System.out.println("value of matrix A"); for(int i=0;i<2;i++) { for(int j=0;j<2;j++) {

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 17 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

System.out.print("a["+i+"]"+"["+j+"] ="); a[i][j]= obj.nextInt(); } } System.out.println("value of matrix B"); for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { System.out.print("b["+i+"]"+"["+j+"] ="); b[i][j]= obj.nextInt(); } } for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { c[i][j]=0; for(int k=0;k<2;k++) c[i][j]= c[i][j]+a[i][k]*b[k][j]; } } }

public static void main(String[] args) { int[][] a = new int[10][12]; int[][] b = new int[2][3]; int[][] c = new int[10][10]; multi(a,b,c); System.out.println("the multiplication of two matrices A * B"); for(int i=0;i<2;i++) {

for(int j=0;j<3;j++) { System.out.print(c[i][j]+" "); } System.out.println(); }} }

Output value of matrix Aa[0][0] =1a[0][1] =3a[1][0] =2a[1][1] =4value of matrix Bb[0][0] =2b[0][1] =0b[0][2] =-4

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 18 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

b[1][0] =3b[1][1] =2b[1][2] =6the multiplication of two matrices A * B11 6 14 16 8 16

Process completed.

LECTURE #15,16

Default values The default values are the values given by the java run time system if we won‟t specify any values. Primitive data types in java A variable of a non-primitive type doesn't contain the value directly; instead, it is a reference (similar to a pointer) to an object. (It is not possible in Java to create user-defined value types). Java has eight primitive types: byte, short, int, long, char, Boolean, float and double. What is the default value for characters? Default values for the characters are the NULL values. Algorithm for displaying the default value of all primitive data types Step1: start Step2: declare a class def Step3: declare some static variables b, s, l, f, d, char c and bl of different data types. Step4: declare a function main() and print the default values of all the data types which we declared. Step5: stop Source code: class def { static byte b; static short s; static int i; static long l; static float f; static double d; static char c; static boolean bl; public static void main(String[] args) { System.out.println("Byte:"+b); System.out.println("Short :"+s); System.out.println("Int :"+i); System.out.println("Long :"+l); System.out.println("Float :"+f); System.out.println("Double :"+d); System.out.println("Char :"+c); System.out.println("Boolean :"+bl); } } Expected output: Byte :0 Short: 0 Int: 0 Long : 0 Float: 0 Double:0 Boolean : false compilejavac def.javarunjava def

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 19 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Develop an algorithm to give an example for command line arguments and code it into java program.Algorithm for command line arguments: Step1: start Step2: declare a class com. Step3: declare a function main() function. Step4: if the length of the arguments equals 0. Step4.1: print no command line arguments. Step5: else print the number of command line arguments length. Step6: initialize i value from 0 to arguments length obtained. Step7: stop. Source code for command line arguments : class com { public static void main(String[] args) { if(args.length==0) System.out.println("no command line arguments"); else { System.out.println("number of command line arguments"); System.out.println(args.length); System.out.println("they are:"); for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } } } } Expected input and output: Javac com.java Java com yes no Number of command line arguments are 2 They are: Yes no

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 20 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #17,18 Searching TechniquesLinear Search Linear search is a very simple search algorithm. In this type of search, a sequential searchis made over all items one by one. Every item is checked and if a match is found then thatparticular item is returned, otherwise the search continues till the end of the datacollection.

AlgorithmLinear Search ( Array A, Value x)Step 1: Set i to 1Step 2: if i > n then go to step 7Step 3: if A[i] = x then go to step 6Step 4: Set i to i + 1Step 5: Go to Step 2Step 6: Print Element x Found at index i and go to step 8Step 7: Print element not foundStep 8: ExitPseudocodeprocedure linear_search (list, value)for each item in the listif match item == valuereturn the item's locationend ifend forend procedure

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 21 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 22 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Binary search Binary search is a fast search algorithm with run-time complexity of Ο(log n). This searchalgorithm works on the principle of divide and conquer. For this algorithm to work properly,the data collection should be in the sorted form. Binary search looks for a particular item by comparing the middle most item of thecollection. If a match occurs, then the index of item is returned. If the middle item isgreater than the item, then the item is searched in the sub-array to the right of the middleitem. Otherwise, the item is searched for in the sub-array to the left of the middle item.This process continues on the sub-array as well until the size of the subarray reduces toHow Binary Search Works?For a binary search to work, it is mandatory for the target array to be sorted. We shalllearn the process of binary search with a pictorial example. The following is our sortedarray and let us assume that we need to search the location of value 31 using binary search

First, we shall determine half of the array by using this formula −mid = low + (high - low) / 2Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Now we compare the value stored at location 4, with the value being searched, i.e. 31.We find that the value at location 4 is 27, which is not a match. As the value is greaterthan 27 and we have a sorted array, so we also know that the target value must be in theupper portion of the array.

17. Bin We change our low to mid + 1 and find the new mid value again.low = mid + 1mid = low + (high - low) / 2Our new mid is 7 now. We compare the value stored at location 7 with our target value31.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 23 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

The value stored at location 7 is not a match, rather it is less than what we are lookingfor. So, the value must be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.

We compare the value stored at location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.Binary search halves the searchable items and thus reduces the count of comparisons tobe made to very less numbers. Binary Search Algorithm:Step1: [Initialize segment variables]Set b=0 , end=n, m=(b+end)/2Step2: repeat steps 3 and 4While (beg<=end and d[m]!=item)Step3: if item<d[m] then end=m-1 otherwise beg=m+1[end of if]Step4: m=(b+end)/2[end of while]Step5: if d[m]=item then l=m otherwise l=Null[end of if]Step6: Exit

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 24 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 25 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #19,20Linked lists

A linked list is a sequence of data structures, which are connected together via links.Linked List is a sequence of links which contains items. Each link contains a connectionanother link. Linked list is the second most-used data structure after array. Followingthe important terms to understand the concept of Linked List. Link − Each link of a linked list can store a data called an element.Next − Each link of a linked list contains a link to the next link called Next.Linked List − A Linked List contains the connection link to the first link calledFirst.

Linked List RepresentationLinked list can be visualized as a chain of nodes, where every node points to the nextnode.

As per the above illustration, following are the important points to be considered. Linked List contains a link element called first. Each link carries a data field(s) and a link field called next. Each link is linked with its next link using its next link. Last link carries a link as null to mark the end of the list.Types of Linked ListFollowing are the various types of linked list. Simple Linked List − Item navigation is forward only. Doubly Linked List − Items can be navigated forward and backward. Circular Linked List − Last item contains link of the first element as next andthe first element has a link to the last element as previous.10. Linked List ─ BasicsBasic OperationsFollowing are the basic operations supported by a list. Insertion − Adds an element at the beginning of the list. Deletion − Deletes an element at the beginning of the list. Display − Displays the complete list. Search − Searches an element using the given key. Delete − Deletes an element using the given key.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 26 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Insertion OperationAdding a new node in linked list is a more than one step activity. We shall learn this withdiagrams here. First, create a node using the same structure and find the location whereit has to be inserted.

Imagine that we are inserting a node B (NewNode), between A (LeftNode) and C(RightNode). Then point B.next to C -

It should look like this −

Algorithm:

Insertion at beginning 1) Allocate memory for new node. 2) Set new_nodedata = val 3) Set new_nodenext = start 4) Set start = new _node 5) End.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 27 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Insertion at end 3) Set new_nodenext = null 4) Set ptr = start 5) Set step 6 while

Ptr next!=NULL 6) Set ptr = ptrnext

[END OF LOOP] 7) Set ptrnext = new_node 8) Exit Search 1) Initialise set ptr = start 2) Repeat step 3 while (ptr)!=NULL 3) If val = ptrdata

Set pos = ptr Gotostep 5 4) Set pos = NULL(-1) 5) Exit

Delete 1) Set ptr = Start 2) Set start = start next 3) Free ptr 4) exit

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 28 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #21,22

Stack A stack is an Abstract Data Type (ADT), commonly used in most programming languages.It is named stack as it behaves like a real-world stack, for example – a deck of cards or apile of plates, etc.A real-world stack allows operations at one end only. For example, we can place or removea card or plate from the top of the stack only. Likewise, Stack ADT allows all dataoperations at one end only. At any given time, we can only access the top element of astack.This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, theelement which is placed (inserted or added) last, is accessed first. In stack terminology,insertion operation is called PUSH operation and removal operation iscalled POP operation.Stack RepresentationThe following diagram depicts a stack and its operations

stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stackcan either be a fixed size one or it may have a sense of dynamic resizing. Here, we aregoing to implement stack using arrays, which makes it a fixed size stack implementation.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 29 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Basic OperationsStack operations may involve initializing the stack, using it and then de-initializing it. Apartfrom these basic stuffs, a stack is used for the following two primary operations − push() − Pushing (storing) an element on the stack. pop() − Removing (accessing) an element from the stack.When data is PUSHed onto stack.To use a stack efficiently, we need to check the status of stack as well. For the samepurpose, the following functionality is added to stacks − peek() − get the top data element of the stack, without removing it. isFull() − check if stack is full. isEmpty() − check if stack is empty.At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointeralways represents the top of the stack, hence named top. The top pointer provides topvalue of the stack without actually removing it.Push OperationThe process of putting a new data element onto stack is known as a Push Operation. Pushoperation involves a series of steps −Step 1 − Checks if the stack is full.Step 2 − If the stack is full, produces an error and exit.Step 3 − If the stack is not full, increments top to point next empty space.Step 4 − Adds data element to the stack location, where top is pointing.Step 5 − Returns success.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 30 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Algorithm for PUSH OperationA simple algorithm for Push operation can be derived as follows −begin procedure push: stack, dataif stack is fullreturn nullendiftop ← top + 1stack[top] ← dataend procedure

Pop OperationAccessing the content while removing it from the stack, is known as a Pop Operation. Inan array implementation of pop() operation, the data element is not actually removed,instead top is decremented to a lower position in the stack to point to the next value. Butin linked-list implementation, pop() actually removes data element and deallocatesmemory space.A Pop operation may involve the following steps −Step 1 − Checks if the stack is empty.Step 2 − If the stack is empty, produces an error and exit.Step 3 − If the stack is not empty, accesses the data element at which top ispointing.Step 4 − Decreases the value of top by 1.Step 5 − Returns success.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 31 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Algorithm for Pop OperationA simple algorithm for Pop operation can be derived as follows −begin procedure pop: stackif stack is emptyreturn nullendifdata ← stack[top]top ← top - 1return dataend procedure

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 32 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #23 , 24

Notation The way to write arithmetic expression is known as a notation. An arithmetic expressioncan be written in three different but equivalent notations, i.e., without changing theessence or output of an expression. These notations are − Infix Notation Prefix (Polish) Notation Postfix (Reverse-Polish) NotationThese notations are named as how they use operator in expression. We shall learn thesame here in this chapter.Infix NotationWe write expression in infix notation, e.g. a-b+c, where operators are used in-betweenoperands. It is easy for us humans to read, write, and speak in infix notation but the samedoes not go well with computing devices. An algorithm to process infix notation could bedifficult and costly in terms of time and space consumption.Prefix NotationIn this notation, operator is prefixed to operands, i.e. operator is written ahead ofoperands. For example, +ab. This is equivalent to its infix notation a+b. Prefix notationis also known as Polish Notation.Postfix NotationThis notation style is known as Reversed Polish Notation. In this notation style, theoperator is postfixed to the operands i.e., the operator is written after the operands. Forexample, ab+. This is equivalent to its infix notation a+b.The following table briefly tries to show the difference in all three notations –

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 33 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

PrecedenceWhen an operand is in between two different operators, which operator will take theoperand first, is decided by the precedence of an operator over others. For example −

As multiplication operation has precedence over addition, b * c will be evaluated first. Atable of operator precedence is provided later.AssociativityAssociativity describes the rule where operators with the same precedence appear in anexpression. For example, in expression a+b−c, both + and – have the same precedence,then which part of the expression will be evaluated first, is determined by associativity ofthose operators. Here, both + and − are left associative, so the expression will beevaluated as (a+b)−c.Precedence and associativity determines the order of evaluation of an expression.Following is an operator precedence and associativity table (highest to lowest) −

The above table shows the default behavior of operators. At any point of time in expressionevaluation, the order can be altered by using parenthesis. For example −In a+b*c, the expression part b*c will be evaluated first, with multiplication asprecedence over addition. We here use parenthesis for a+b to be evaluated first,like (a+b)*c.Postfix Evaluation AlgorithmWe shall now look at the algorithm on how to evaluate postfix notation −Step 1 − scan the expression from left to rightStep 2 − if it is an operand push it to stackStep 3 − if it is an operator pull operand from stack and perform operationStep 4 − store the output of step 3, back to stackStep 5 − scan the expression until all operands are consumedStep 6 − pop the stack and perform operation

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 34 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

The common arithmetic expression are written in infix notation such as A*B+C*DPolish mathematician Lukasiewicz showed that arithmetic expressions can be represented in prefix notation This representation , often referred to as Polish notation, places the operator before the operands.The postfix notation, referred to as reverse Polish notation(RPN) places the operator after the operands. The following examples demonstrate the three representations:A+B infix notation+AB Prefix or Polish notationAB+ Postfix or reverse Polish notationScientific calculators that employ an internal stack require that the user convert arithmetic expression into reverse polish notation. Computers that use a stack organized CPU provide a system program to perform the conversion for the user.Stack operation to evaluate 3*4+5*6

34*56*+

3 6 *

5 6 * +

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 35 of 61

343 123

512

6512

3

3012 42

3

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #25 , 26

QueueQueue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queueis open at both its ends. One end is always used to insert data (enqueue) and the other isused to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., thedata item stored first will be accessed first.

A real-world example of queue can be a single-lane one-way road, where the vehicle entersfirst, exits first. More real-world examples can be seen as queues at the ticket windowsand bus-stops.Queue RepresentationAs we now understand that in queue, we access both ends for different reasons. Thefollowing diagram given below tries to explain queue representation as data structure −

As in stacks, a queue can also be implemented using Arrays, Linked-lists, Pointers andStructures. For the sake of simplicity, we shall implement queues using one-dimensionalarray.

Basic OperationsQueue operations may involve initializing or defining the queue, utilizing it, and thencompletely erasing it from the memory. Here we shall try to understand the basicoperations associated with queues − enqueue() − add (store) an item to the queue. dequeue() − remove (access) an item from the queue.Few more functions are required to make the above-mentioned queue operation efficient.These are − peek() − Gets the element at the front of the queue without removing it. isfull() − Checks if the queue is full.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 36 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

isempty() − Checks if the queue is empty.In queue, we always dequeue (or access) data, pointed by front pointer and whileenqueing (or storing) data in the queue we take help of rear pointer.Let's first learn about supportive functions of a queue −

Enqueue OperationQueues maintain two data pointers, front and rear. Therefore, its operations arecomparatively difficult to implement than that of stacks.The following steps should be taken to enqueue (insert) data into a queue − Step 1 − Check if the queue is full. Step 2 − If the queue is full, produce overflow error and exit. Step 3 − If the queue is not full, increment rear pointer to point the next emptyspace. Step 4 − Add data element to the queue location, where the rear is pointing. Step 5 − Return success.

Sometimes, we also check to see if a queue is initialized or not, to handle any unforeseensituations.Algorithm for enqueue Operationprocedure enqueue(data)if queue is fullreturn overflowendifrear ← rear + 1queue[rear] ← datareturn trueend procedure

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 37 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

int enqueue(int data)if(isfull())return 0;rear = rear + 1;queue[rear] = data;return 1;end procedureDequeue OperationAccessing data from the queue is a process of two tasks − access the data where front ispointing and remove the data after access. The following steps are taken toperform dequeue operation −Step 1 − Check if the queue is empty.Step 2 − If the queue is empty, produce underflow error and exit.Step 3 − If the queue is not empty, access the data where front is pointing.Step 4 − Increment front pointer to point to the next available data element.Step 5 − Return success.

Algorithm for dequeue Operationprocedure dequeueif queue is emptyreturn underflowend ifdata = queue[front]

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 38 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

front ← front + 1return trueend procedure

LECTURE #27 , 28

Hash TableHash Table is a data structure which stores data in an associative manner. In a hash table,data is stored in an array format, where each data value has its own unique index value.Access of data becomes very fast if we know the index of the desired data.Thus, it becomes a data structure in which insertion and search operations are very fastirrespective of the size of the data. Hash Table uses an array as a storage medium anduses hash technique to generate an index where an element is to be inserted or is to belocated from.HashingHashing is a technique to convert a range of key values into a range of indexes of an array.We're going to use modulo operator to get a range of key values. Consider an example ofhash table of size 20, and the following items are to be stored. Item are in the (key,value)format.

(1,20)(2,70)(42,80)(4,25)(12,44)(14,32)(17,11)(13,78)(37,98)

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 39 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Linear ProbingAs we can see, it may happen that the hashing technique is used to create an already usedindex of the array. In such a case, we can search the next empty location in the array bylooking into the next cell until we find an empty cell. This technique is called linear probing.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 40 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Basic OperationsFollowing are the basic primary operations of a hash table.Search − Searches an element in a hash table.Insert − inserts an element in a hash table.Delete − Deletes an element from a hash table.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 41 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #29 , 30

Graph Data StructureA graph is a pictorial representation of a set of objects where some pairs of objects areconnected by links. The interconnected objects are represented by points termedas vertices, and the links that connect the vertices are called edges.Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set ofedges, connecting the pairs of vertices. Take a look at the following graph −

In the above graph,V = {a, b, c, d, e}E = {ab, ac, bd, cd, de}Graph Data StructureMathematical graphs can be represented in data structure. We can represent a graph usingan array of vertices and a two-dimensional array of edges. Before we proceed further, let'sfamiliarize ourselves with some important terms − Vertex − Each node of the graph is represented as a vertex. In the followingexample, the labeled circle represents vertices. Thus, A to G are vertices. We canrepresent them using an array as shown in the following image. Here A can beidentified by index 0. B can be identified using index 1 and so on.Edge − Edge represents a path between two vertices or a line between twovertices. In the following example, the lines from A to B, B to C, and so onrepresents edges. We can use a two-dimensional array to represent an array asshown in the following image. Here AB can be represented as 1 at row 0, column1, BC as 1 at row 1, column 2 and so on, keeping other combinations as 0. Adjacency − Two node or vertices are adjacent if they are connected to eachother through an edge. In the following example, B is adjacent to A, C is adjacentto B, and so on. Path − Path represents a sequence of edges between the two vertices. In thefollowing example, ABCD represents a path from A to D.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 42 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Basic OperationsFollowing are the basic primary operations that can be performed on a Graph:Add Vertex − Adds a vertex to the graph.Add Edge − Adds an edge between the two vertices of the graph.Display Vertex − Displays a vertex of the graph.To know more about Graph, please read Graph Theory Tutorial. We shall learn abouttraversing a graph in the coming chapters.

Depth First Search (DFSDepth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 43 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

As in the example given above, DFS algorithm traverses from A to B to C to D first thento E, then to F and lastly to G. It employs the following rules.Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push itin a stack.Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It willpop up all the vertices from the stack, which do not have adjacent vertices.)Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 44 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 45 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 46 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #31 , 32

Breadth First Search (BFS)Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and usesa queue to remember to get the next vertex to start a search, when a dead end occurs inany iteration.

As in the example given above, BFS algorithm traverses from A to B to E to F first then toC and G lastly to D. It employs the following rules.Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insertit in a queue.Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 47 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 48 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 49 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithmwe keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied,the program is over.

LECTURE #33 , 34

Tree Data StructureTreeTree represents the nodes connected by edges. We will discuss binary tree or binary searchtree specifically. Binary Tree is a special datastructure used for data storage purposes. A binary tree has aspecial condition that each node can have a maximum of two children. A binary tree hasthe benefits of both an ordered array and a linked list as search is as quick as in a sortedarray and insertion or deletion operation are as fast as in linked list.

Important TermsFollowing are the important terms with respect to tree.Path − Path refers to the sequence of nodes along the edges of a tree.Root – The node at the top of the tree is called root. There is only one root pertree and one path from the root node to any node.Parent − Any node except the root node has one edge upward to a node called

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 50 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

parent.Child – The node below a given node connected by its edge downward is called itschild node.Leaf – The node which does not have any child node is called the leaf node.Subtree − Subtree represents the descendants of a node.Visiting − Visiting refers to checking the value of a node when control is on thenode.Traversing − Traversing means passing through nodes in a specific order.Levels − Level of a node represents the generation of a node. If the root node isat level 0, then its next child node is at level 1, its grandchild is at level 2, and soon.

Keys − Key represents a value of a node based on which a search operation is tobe carried out for a node.

Binary Search Tree RepresentationBinary Search tree exhibits a special behavior. A node's left child must have a value lessthan its parent's value and the node's right child must have a value greater than its parent

We're going to implement tree using node object and connecting them through references.BST Basic OperationsThe basic operations that can be performed on a binary search tree data structure, arethe following −Insert − Inserts an element in a tree/create a tree.Search − Searches an element in a tree.Pre-order Traversal − Traverses a tree in a pre-order manner.In-order Traversal − Traverses a tree in an in-order manner.Post-order Traversal − Traverses a tree in a post-order manner.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 51 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 52 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #35 , 36

Traversing a binary tree Traversal is a process to visit all the nodes of a tree and may print their values too.Because, all nodes are connected via edges (links) we always start from the root (head)node. That is, we cannot randomly access a node in a tree. There are three ways whichwe use to traverse a tree −In-order TraversalPre-order TraversalPost-order TraversalGenerally, we traverse a tree to search or locate a given item or key in the tree or to printall the values it contains.In-order TraversalIn this traversal method, the left subtree is visited first, then the root and later the rightsub-tree. We should always remember that every node may represent a subtree itself.If a binary tree is traversed in-order, the output will produce sorted key values in anascending order.

We start from A, and following in-order traversal, we move to its left subtree B. B is alsotraversed in-order. The process goes on until all the nodes are visited. The output of inordertraversal of this tree will be −D → B → E → A → F → C → GAlgorithmUntil all nodes are traversed −Step 1 − Recursively traverse left subtree.Step 2 − Visit root node.Step 3 − Recursively traverse right subtree.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 53 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Pre-order TraversalIn this traversal method, the root node is visited first, then the left subtree and finally theright subtree.

We start from A, and following pre-order traversal, we first visit A itself and then move toits left subtree B. B is also traversed pre-order. The process goes on until all the nodesare visited. The output of pre-order traversal of this tree will be −A → B → D → E → C → F → GAlgorithmUntil all nodes are traversed −Step 1 − Visit root node.Step 2 − Recursively traverse left subtree.Step 3 − Recursively traverse right subtree.

Post-order TraversalIn this traversal method, the root node is visited last, hence the name. First we traversethe left subtree, then the right subtree and finally the root node.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 54 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

We start from A, and following pre-order traversal, we first visit the left subtree B. B isalso traversed post-order. The process goes on until all the nodes are visited. The outputof post-order traversal of this tree will be −D → E → B → F → G → C → AAlgorithmUntil all nodes are traversed −Step 1 − Recursively traverse left subtree.Step 2 − Recursively traverse right subtree.Step 3 − Visit root node.

LECTURE #37 , 38Binary Search Tree (BST)A Binary Search Tree (BST) is a tree in which all the nodes follow the below-mentionedproperties − The left sub-tree of a node has a key less than or equal to its parent node's key. The right sub-tree of a node has a key greater than or equal to its parent node'skey.Thus, BST divides all its sub-trees into two segments; the left sub-tree and the right subtreeand can be defined as −left_subtree (keys) ≤ node (key) ≤ right_subtree (keys) RepresentationBST is a collection of nodes arranged in a way where they maintain BST properties. Eachnode has a key and an associated value. While searching, the desired key is compared tothe keys in BST and if found, the associated value is retrieved.Following is a pictorial representation of BST −We observe that the root node key (27) has all less-valued keys on the left sub-tree andthe higher valued keys on the right sub-tree.32. Binary Search Tree

We observe that the root node key (27) has all less-valued keys on the left sub-tree andthe higher valued keys on the right sub-tree.Basic Operations

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 55 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Following are the basic operations of a tree -Search − Searches an element in a tree.Insert − Inserts an element in a tree.Pre-order Traversal − Traverses a tree in a pre-order manner.In-order Traversal − Traverses a tree in an in-order manner.Post-order Traversal − Traverses a tree in a post-order mann

LECTURE #39, 40

HeapHeap is a special case of balanced binary tree data structure where the root-node key iscompared with its children and arranged accordingly. If α has child node β then −key(α) ≥ key(β)As the value of parent is greater than that of child, this property generates Max Heap.Based on this criteria, a heap can be of two types −For Input → 35 33 42 10 14 19 27 44 26 31Min-Heap − Where the value of the root node is less than or equal to either of its children.Max-Heap − Where the value of the root node is greater than or equal to either of itschildren.35. Heaps

Max-Heap − Where the value of the root node is greater than or equal to either of itschildren.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 56 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Both trees are constructed using the same input and order of arrival.

Max Heap Construction AlgorithmWe shall use the same example to demonstrate how a Max Heap is created. The procedureto create Min Heap is similar but we go for min values instead of max values.We are going to derive an algorithm for max heap by inserting one element at a time. Atany point of time, heap must maintain its property. While insertion, we also assume thatwe are inserting a node in an already heapified tree.Step 1 − Create a new node at the end of heap.Step 2 − Assign new value to the node.Step 3 − Compare the value of this child node with its parent.Step 4 − If value of parent is less than child, then swap them.Step 5 − Repeat step 3 & 4 until Heap property holds.Note − In Min Heap construction algorithm, we expect the value of the parent node to beless than that of the child node.Let's understand Max Heap construction by an animated illustration. We consider the sameinput sample that we used earlier.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 57 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Max Heap Deletion AlgorithmLet us derive an algorithm to delete from max heap. Deletion in Max (or Min) Heap alwayshappens at the root to remove the Maximum (or minimum) value.Step 1 − Remove root node.Step 2 − Move the last element of last level to root.Step 3 − Compare the value of this child node with its parent.Step 4 − If value of parent is less than child, then swap them.Step 5 − Repeat step 3 & 4 until Heap property holds.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 58 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

LECTURE #41 42RecursionSome computer programming languages allow a module or function to call itself. Thistechnique is known as recursion. In recursion, a function α either calls itself directly orcalls a function β that in turn calls the original function α. The function α is called recursivefunction.PropertiesA recursive function can go infinite like a loop. To avoid infinite running of recursivefunction, there are two properties that a recursive function must have −Base criteria − There must be at least one base criteria or condition, such that,when this condition is met the function stops calling itself recursively.Progressive approach − The recursive calls should progress in such a way thateach time a recursive call is made it comes closer to the base criteria.

ImplementationMany programming languages implement recursion by means of stacks. Generally,whenever a function (caller) calls another function (callee) or itself as callee, the callerfunction transfers execution control to the callee. This transfer process may also involvesome data to be passed from the caller to the callee.This implies, the caller function has to suspend its execution temporarily and resume laterwhen the execution control returns from the callee function. Here, the caller function needsto start exactly from the point of execution where it puts itself on hold. It also needs theexact same data values it was working on. For this purpose, an activation record (or stackframe) is created for the caller function.

This activation record keeps the information about local variables, formal parameters,return address and all information passed to the caller function.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 59 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

Analysis of RecursionOne may argue why to use recursion, as the same task can be done with iteration. Thefirst reason is, recursion makes a program more readable and because of latest enhancedCPU systems, recursion is more efficient than iterations.Time ComplexityIn case of iterations, we take number of iterations to count the time complexity. Likewise,in case of recursion, assuming everything is constant, we try to figure out the number oftimes a recursive call is being made. A call made to a function is Ο(1), hence the (n)number of times a recursive call is made makes the recursive function Ο(n).Space ComplexitySpace complexity is counted as what amount of extra space is required for a module toexecute. In case of iterations, the compiler hardly requires any extra space. The compilerkeeps updating the values of variables used in the iterations. But in case of recursion, thesystem needs to store activation record each time a recursive call is made. Hence, it isconsidered that space complexity of recursive function may go higher than that of afunction with iteration.

Tower of HanoiTower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and morethan one rings is as depicted −

These rings are of different sizes and stacked upon in an ascending order, i.e. the smallerone sits over the larger one. There are other variations of the puzzle where the number ofdisks increase, but the tower count remains the same

RulesThe mission is to move all the disks to some another tower without violating the sequenceof arrangement. A few rules to be followed for Tower of Hanoi are −Only one disk can be moved among the towers at any given time.Only the "top" disk can be removed.No large disk can sit over a small disk.

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 60 of 61

Data Structures and Algorithm Semester: 3rd Year: 2nd

AlgorithmTo write an algorithm for Tower of Hanoi, first we need to learn how to solve this problemwith lesser amount of disks, say → 1 or 2. We mark three towers withname, source, destination and aux (only to help moving the disks). If we have only onedisk, then it can easily be moved from source to destination peg.If we have 2 disks – First, we move the smaller (top) disk to aux peg. Then, we move the larger (bottom) disk to destination peg. And finally, we move the smaller disk from aux to destination peg. So now, we are in a position to design an algorithm for Tower of Hanoi with more thantwo disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in onepart and all other (n-1) disks are in the second part.Our ultimate aim is to move disk n from source to destination and then put all other (n-1) disks onto it. We can imagine to apply the same in a recursive way for all given set ofdisks.The steps to follow are −Step 1 − Move n-1 disks from source to auxStep 2 − Move nth disk from source to destStep 3 − Move n-1 disks from aux to destA recursive algorithm for Tower of Hanoi can be driven as follows −STARTProcedure Hanoi(disk, source, dest, aux)IF disk == 0, THENmove disk from source to destELSEHanoi(disk - 1, source, aux, dest) // Step 1move disk from source to dest // Step 2Hanoi(disk - 1, aux, dest, source) // Step 3END IFEND ProcedureSTOP

By Engr. Shafiya Qadeer Memon(Assistant professor) Dept: SWE MUET, Jamshoro Page 61 of 61