Data structure and algorithm All in One

107
Data Structure and Algorithm Prepared by Basharat Jehan Email: [email protected]

Transcript of Data structure and algorithm All in One

Page 1: Data structure and algorithm All in One

Data Structure and Algorithm

Prepared by Basharat JehanEmail: [email protected]

Page 2: Data structure and algorithm All in One

Data• Facts or information used usually to calculate, analyze, or

plan something.OR

• Data are simply collection of facts and figures. Data are values or set of values.

ORThe quantities, characters, or symbols on which operations are performed by a computer, being stored and transmitted in the form of electrical signals and recorded on magnetic, optical, or mechanical recording media.

Page 3: Data structure and algorithm All in One

• In computing, data is information that has been translated into a form that is more convenient to move or process.

• Data is collected and analyzed to create information suitable for making decisions

Page 4: Data structure and algorithm All in One

• Data items that are divided into sub items are group items;

• those that are not are called elementary items. For example, a student’s name may be divided into three sub items – [first name, middle name and last name]

• but the ID of a student would normally be treated as a single item.

Page 5: Data structure and algorithm All in One
Page 6: Data structure and algorithm All in One

Information

• Knowledge that you get about someone or something.

• knowledge obtained from investigation, study, or instruction (2) : intelligence, news (3) : facts, data .

• Data are converted to information after Processing.

• knowledge gained through study, communication, research, instruction, etc.; factual data:

Page 7: Data structure and algorithm All in One

• Data that is (1) accurate and timely, (2) specific and organized for a purpose, (3) presented within a context that gives it meaning and relevance, and (4) can lead to an increase in understanding and decrease in uncertainty.

Page 8: Data structure and algorithm All in One

Field, Record and File

Page 9: Data structure and algorithm All in One

Data Structure

• In computer science, a data structure is a particular way of organizing data in a computer so that it can be used efficiently.

Page 10: Data structure and algorithm All in One
Page 11: Data structure and algorithm All in One
Page 12: Data structure and algorithm All in One

Algorithm Notations

Page 13: Data structure and algorithm All in One
Page 14: Data structure and algorithm All in One
Page 15: Data structure and algorithm All in One

Physical and Logical Data Structures

• A physical data structure refers to the actual organization of data on a storage device. The logical data structure refers to how the information appears to a program or user. For example, a data file is a collection of information stored together. This is its logical structure. Physically, however, a file could be stored on a disk in several scattered pieces.

Page 16: Data structure and algorithm All in One

ALGORITHM

Page 17: Data structure and algorithm All in One

INTRODUCTION

• An algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function

Page 18: Data structure and algorithm All in One

COMPUTER ALGORITHMS

• In computer systems, an algorithm is basically an instance of logic written in software by software developers to be effective for the intended "target" computer(s) for the target machines to produce output from given input (perhaps null)

Page 19: Data structure and algorithm All in One

DEFINITION• An algorithm is a finite sequence of step by

step, discrete, unambiguous instructions for solving a particular problem

– has input data, and is expected to produce output data

– each instruction can be carried out in a finite amount of time in a deterministic way

Page 20: Data structure and algorithm All in One

Control structures• Programs written in procedural languages, the most

common kind, are like recipes, having lists of ingredients and step-by-step instructions for using them. The three basic control structures in virtually every procedural language are:

1. Sequence—combine the liquid ingredients, and next add the dry ones.

2. Conditional—if the tomatoes are fresh then simmer them, but if canned, skip this step.

3. Iterative—beat the egg whites until they form soft peaks.

Page 21: Data structure and algorithm All in One

SEQUENCE

• it is the default control structure; instructions are executed one after another. They might, for example, carry out a series of arithmetic operations, assigning results to variables, to find the roots of a quadratic equationax2 + bx + c = 0. The conditional IF-THEN or IF-THEN-ELSE control structure allows a program to follow alternative paths of execution.

Page 22: Data structure and algorithm All in One

ITERATIVE/REPETITIVE FLOW

• Iteration (also called repetition) means a frame that regulates the repeat of an action depending on a condition. The action is called the body of the iteration loop.

• This means that all low or high level algorithms can be formulated as a series of structural elements consisting only of the three types above.

• Hence, for any algorithm description method it is enough to be able to interpret the three types above.

Page 23: Data structure and algorithm All in One

The flow diagram of the minimum finding problem

Page 24: Data structure and algorithm All in One

ITERATION, OR LOOPING AND CONDITIONAL FLOW

• It gives computers much of their power. They can repeat a sequence of steps as often as necessary, and appropriate repetitions of quite simple steps can solve complex problems.

• These control structures can be combined. A sequence may contain several loops; a loop may contain a loop nested within it, or the two branches of a conditional may each contain sequences with loops and more conditionals. The following programming fragment employs the IF-THEN structure for finding one root of the quadratic equation, using the quadratic formula:

Page 25: Data structure and algorithm All in One

Array data structure

• In computer science, an array data structure or simply an array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key.

Page 26: Data structure and algorithm All in One

FINDING LENGTH OF ARRY

• MAXIMUM LENGTH= UPPER BOUND(UB)-LOWER BOUND(LB)+1

Page 27: Data structure and algorithm All in One

One dimensional (1-D) arrays or Linear arrays:

• In it each element is represented by a single subscript. The elements are stored in consecutive memory locations. E.g. A [1], A [2], ….., A [N].

• Or• A(1), A(2)…• A1,A2,…………

Page 28: Data structure and algorithm All in One

Multi dimensional arrays: Two dimensional (2-D) arrays or Matrix arrays

• In it each element is represented by two subscripts. Thus a two dimensional m x n array A has m rows and n columns and contains m*n elements. It is also called matrix array because in it the elements form a matrix. E.g. A [2] [3] has 2 rows and 3 columns and 2*3 = 6 elements.

Page 29: Data structure and algorithm All in One

Traversing

• Traversing basically means the accessing the each and every element of the array at least once. Traversing is usually done to be aware of the data elements which are present in the array.

Page 30: Data structure and algorithm All in One

ALGORITHM FOR TRAVERSING

• SET K=LB• REPEAT STEP 3 AND 4 WHILE K<=UB• INPUT ARRAY[K]• SET K=K+1• END LOOP• OUTPUT ARRAY[K]• EXIT

Page 31: Data structure and algorithm All in One

A program to traverse or read a linear or 1-D array

• #include<stdio.h>#include<conio.h>void main(){int a[7], i=0;clrscr();printf("Enter the elements of the array :");for (i=0;i<=6 ;i++ ){ scanf("%d\n", &a[i]); /* taking input array from the user */ }printf("\nThe elements of the array you have enetered are as follows :")for(i=0; i<=6; i++) { printf("%d", a[i]); /* printing the array elements or traversing the array */}getch();}

Page 32: Data structure and algorithm All in One

Algorithm to find the sum of elements of array

• Step#1 SUM=0• Step#2 repeat for i=0 to UB• [print the calculated sum]

• SUM=SUM+A[i]• End of Loop

• Step#3 PRINT SUM• Step#4 EXIT

Page 33: Data structure and algorithm All in One

Program• #include<iostream.h>• #include<conio.h>• using namespace std;• main()• {• int A[3], sum,i;• sum=0;• for(i=0; i<=2;i++)• {• cin>>A[i];• sum=sum+A[i];•• }• cout<<sum;• getch();• }

Page 34: Data structure and algorithm All in One

Accessing One Dimensional array by Dope Vector method

• L(X[k])=Lo+C*(k-1)• Where Lo is base address, C is the length of

each memory location, and k is index number.

• L(X[3]) = 200+2*(3-1)=204

Data address45 20045 202

56 204

67 206

88 208

Page 35: Data structure and algorithm All in One
Page 36: Data structure and algorithm All in One

representing 2D array in memory

Page 37: Data structure and algorithm All in One
Page 38: Data structure and algorithm All in One

Inserting

• Inserting: Adding a new record to the end of array.

• Insertion may be at end of array or at specific location.

Page 39: Data structure and algorithm All in One

• Adding a new record to the end of array.• Algorithm

• REPEAT step 2 to 3 FOR I=4 to 9• INPUT value in N• Temp[I]= N[End of step- 2 Loop]Exit

Page 40: Data structure and algorithm All in One

• #include<iostream>• #include<conio.h>• using namespace std;• class insrt• {•• private:• int i, A[10];• public:• void input()• {• A[1]=10;• A[2]=20;• }• void abc()• {• for(i=3; i<=10; i++)• {• cin>>A[i];

• }• for(i=1; i<=10; i++)• {• cout<<A[i];• }• }};• main()• {• insrt a;• a.input();• a.abc();

• }

Page 41: Data structure and algorithm All in One

Element insertion at specific location

• Algorithm to insert element in array requires the specific location at which the element is to be added.

Page 42: Data structure and algorithm All in One
Page 43: Data structure and algorithm All in One

• This algorithm performs Insert Operation on Array; it adds an ELEMENT at the given location LOC in the array – DATA. In the first step we initialized variable I with the maximum number of element present in the array (I:=N). After that with loop we shift the element forward till we reach the location LOC. In the next step, we insert the ELEMENT at its location.

Page 44: Data structure and algorithm All in One

• #include<iostream>• #include<conio.h>• using namespace std;• class bcs• {• private:• int abc[5],i;• public:• void assign(int j)• {• for(int i=0; i<=j; i++)• cin>>abc[i];•• void specific(int loc, int val)• {• for(int i=4; i>=loc; i--)• abc[i+1]=abc[i];• abc[loc]=val;• }

Page 45: Data structure and algorithm All in One

• void print(int n)• {• for(int i=0; i<=n; i++)• cout<<abc[i];• }• };• main()• {• bcs obj;• int n,pos;• obj.assign(3);• obj.print(3);

• cout<<"enter value to insert";• cin>>n>>endl;• cin>>pos;• if(pos>=4)• {• cout<<"invalid location";• return 0;• }• obj.specific(pos,n);• obj.print(4);• }

Page 46: Data structure and algorithm All in One

Useful link

• http://www.enjoylearningcs.com/array-operation-insert-delete-element/

Page 47: Data structure and algorithm All in One
Page 48: Data structure and algorithm All in One
Page 49: Data structure and algorithm All in One

Delete Operation on Array

• To delete element from array we should know the location from where we want to delete. Algorithm to Delete Element from Array can be executed at any location ie. at it beginning, in middle or at the end of the array.

• Apply a loop from the location of item till the end of the array. Shift the element forward. In this algorithm, DATA is an array. ELEMENT is the value which we want to delete from the location LOC. N is the maximum number of element present in the array DATA.

Page 50: Data structure and algorithm All in One

Algorithm to Delete Element from Array is:

Page 51: Data structure and algorithm All in One
Page 52: Data structure and algorithm All in One
Page 53: Data structure and algorithm All in One

INTRODUCTION TO THE BASIC OPERATIONS OF DATA STRUCTURE• The data appearing in data structures are

processed by means of operations. The following are operations are major operations

Page 54: Data structure and algorithm All in One

• Traversing: Accessing each record exactly once so that certain items in the record may be processed.

• Searching: Finding the location of the record with a given key value, or finding the locations of all records which satisfy one or more conditions.

• Inserting: Adding a new record to the structure.• Deleting: Removing a record from the structure.

It is used to delete an existing data item from the given collection of data items

Page 55: Data structure and algorithm All in One

Following two are special operations:

Following two are special operations:• Sorting: Arranging the records in some logical

order. It is used to arrange the data items in some order i.e. in ascending or descending order in case of numerical data and in dictionary order in case of alphanumeric data

• Merging: Combining the records in two different sorted files into a single sorted file.

Page 56: Data structure and algorithm All in One

Recursion Concept :

• Recursion is basic concept in Programming.• When Function is defined in terms of itself

then it is called as “Recursion Function“.• Recursive function is a function which

contains a call to itself.

Page 57: Data structure and algorithm All in One
Page 58: Data structure and algorithm All in One
Page 59: Data structure and algorithm All in One

59

Page 60: Data structure and algorithm All in One

Fibonacci Sequence

• The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. Similarly, the 3 is found by adding the two numbers before it (1+2),

Page 61: Data structure and algorithm All in One

Fibonacci series program in c using recursion

• #include<stdio.h>• • int Fibonacci(int);• • main()• {• int n, i = 0, c;• • cin>>n;• • cout<<"Fibonacci series;• • for ( c = 1 ; c <= n ; c++ )• {• cout<<Fibonacci(i);• i++; • }• • return 0;• }•

Page 62: Data structure and algorithm All in One

• int Fibonacci(int n)• {• if ( n == 0 )• return 0;• else if ( n == 1 )• return 1;• else• return ( Fibonacci(n-1) + Fibonacci(n-2) );• }

Page 63: Data structure and algorithm All in One

Searching Algorithms

• Necessary components to search a list of fdata– Array containing the list– Length of the list– Item for which you are searching

• After search completed– If item found, report “success,” return location in array – If item not found, report “not found” or “failure”

Page 64: Data structure and algorithm All in One

Sequential Search

• In computer science, linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted. The list need not be ordered.

Page 65: Data structure and algorithm All in One

• Suppose that you want to determine whether 27 is in the list • First compare 27 with list[0]; that is, compare 27 with 35

• Because list[0] ≠ 27, you then compare 27 with list[1]

• Because list[1] ≠ 27, you compare 27 with the next element in the list

• Because list[2] = 27, the search stops• This search is successful!

Searching Algorithms (Cont’d)

Figure 1: Array list with seven (07) elements

Page 66: Data structure and algorithm All in One

• Let’s now search for 10 • The search starts at the first element in the list; that

is, at list[0]• Proceeding as before, we see that this time the

search item, which is 10, is compared with every item in the list

• Eventually, no more data is left in the list to compare with the search item; this is an unsuccessful search

Searching Algorithms (Cont’d)

Page 67: Data structure and algorithm All in One

Algorithm of Sequential Searching• The complete algorithm for sequential search is//list the elements to be searched//target the value being searched for//N the number of elements in the list

SequentialSearch( LIST, ITEM, N, LOC)Set LOC=1• for i = 1 to N do• INPUT LIST[i]• Repeat While(LOC<=N) • if (ITEM = LIST[LOC])• return LOC[Successful Search]• LOC=LOC+1• end if• end While• return 0 [Unsuccessful Search]

Page 68: Data structure and algorithm All in One

C++ Code for Sequential Search

• #include<iostream>• #include<conio.h>• using namespace std;• main()• {• int A[10],i, LOC, ITEM,n;• LOC=-1;• cout<<"Enter size of array but less than 10";• cin>>n;

Page 69: Data structure and algorithm All in One

• for (i=1; i<=n; i++)• {• cin>>A[i];• }• cout<<"item to be searched";• cin>>ITEM;

Page 70: Data structure and algorithm All in One

• i=0;• while(i<=n)• {• if (ITEM==A[i]){• LOC=i;• cout<<"location"<<LOC;• }• i++;• }

Page 71: Data structure and algorithm All in One

• if(LOC==-1)• {•• cout<<"data not found";• }• }

Page 72: Data structure and algorithm All in One

• Can only be performed on a sorted list !!!

• Uses divide and conquer technique to search list

Binary Search Algorithm

Page 73: Data structure and algorithm All in One

• Search item is compared with middle element of list

• If search item < middle element of list, search is restricted to first half of the list

• If search item > middle element of list, search second half of the list

• If search item = middle element, search is complete

Binary Search Algorithm (Cont’d)

Page 74: Data structure and algorithm All in One

• Determine whether 75 is in the list

Binary Search Algorithm (Cont’d)

Figure 2: Array list with twelve (12) elements

Figure 3: Search list, list[0] … list[11]

Page 75: Data structure and algorithm All in One

Binary Search Algorithm (Cont’d)

Figure 4: Search list, list[6] … list[11]

Page 76: Data structure and algorithm All in One
Page 77: Data structure and algorithm All in One

C++ program for binary search• #include<iostream>• #include<conio.h>• using namespace std;• main()• {• int a[10], loc,item,n,i;• Loc=-1;• cout<<"enter size of array"<<endl;• cin>>n;• for(i=1; i<=n; i++)• {• cin>>a[i];•• }• for(i=1; i<=n; i++)• {• cout<<"array element"<<a[i]<<endl;• }•

Page 78: Data structure and algorithm All in One

• cout<<"enter item to be searched "<<endl;• cin>>item;• int middle=(1+n)/2;• cout<<middle;• if(item==a[middle])• {• cout<<middle;• }

Page 79: Data structure and algorithm All in One

• if(item>a[middle])• {• i=middle+1;• while(i<=n)• {• if(item==a[i])• {• Loc=i;• cout<<loc;• }• i++;• }}•

Page 80: Data structure and algorithm All in One

• if(item<a[middle])• {• i=middle-1;• while(i>0)• {• if(item==a[i])• {• i=loc;• cout<<loc;• }• i--;• }}

• if(loc==-1)• {• cout<<"item not found";• }• }

Page 81: Data structure and algorithm All in One

Sorting

• Definition is discussed already in previous slides.. See data structure operations types

Page 82: Data structure and algorithm All in One

Bubble Sort

• The technique we use is called “Bubble Sort” because the bigger value gradually bubbles their way up to the top of array like air bubble rising in water, while the small values sink to the bottom of array.

Page 83: Data structure and algorithm All in One
Page 84: Data structure and algorithm All in One

• Algorithm: (Bubble Sort) BUBBLE (DATA, n)• Here DATA is an Array with N elements. This algorithm sorts the• elements in DATA.• 1. for(pass=n; pass>=1; pass--)• 2. for(i=1; i<=pass; i++)• 3. If DATA[i]>DATA[i+1], then:• Interchange DATA[i] and DATA[i+1].• [End of If Structure.]• [End of inner loop.]• [End of Step 1 outer loop.]• 4. Exit.

Page 85: Data structure and algorithm All in One

C++ PROGRAMM FOR BUBBLE SORT• #include<iostream>• #include<conio.h>• using namespace std;• main()• {• int pass,n,i,temp;• int a[10];• cout<<"PROGRAM FOR BUBBLE SORT";• cout<<"Enter size of array which is less than 10";• cin>>n;• for(i=1; i<=n; i++)• {• cin>>a[i];• }•

Page 86: Data structure and algorithm All in One

• for(pass=n; pass>=1; pass--)•• for(i=1; i<=pass; i++)•• if(a[i]>a[i+1])• {• temp=a[i+1];• a[i+1]=a[i];• a[i]=temp;• }•• for(i=1; i<=n; i++)• {• cout<<a[i];• }•• }

Page 87: Data structure and algorithm All in One

Insertion Sort

• Sorting method in which algorithm scan a whole list one by one and in each iteration the algorithm place each number to its correct position.

Page 88: Data structure and algorithm All in One

example

Page 89: Data structure and algorithm All in One
Page 90: Data structure and algorithm All in One

algorithm

Page 91: Data structure and algorithm All in One

See example animated example at

• http://courses.cs.vt.edu/csonline/Algorithms/Lessons/InsertionCardSort/insertioncardsort.swf

Page 92: Data structure and algorithm All in One

STACKS

• It is an ordered group of homogeneous items of elements. Elements are added to and removed from the top of the stack (the most recently added items are at the top of the stack). The last element to be added is the first to be removed (LIFO: Last In, First Out).

Page 93: Data structure and algorithm All in One
Page 94: Data structure and algorithm All in One

• A stack is a list of elements in which an element may be inserted or deleted only at

• one end, called TOP of the stack. The elements are removed in reverse order of that in which they were inserted into the stack.

Page 95: Data structure and algorithm All in One

• Basic operations:• These are two basic operations associated

with stack:• Push() is the term used to insert/add an

element into a stack.• Pop() is the term used to delete/remove an

element from a stack.

Page 96: Data structure and algorithm All in One
Page 97: Data structure and algorithm All in One

Stack push and pop program

• #include<iostream>• #include<conio.h>• using namespace std;• main()• {• int s[10], i,j,n;

• int top=0;

Page 98: Data structure and algorithm All in One

• do• {• cin>>j;• s[top+1]=j;• for(j=top+1; j>=1;j--)• cout<<s[j]<<endl;• top++;• cout<<"do you want to process more

y/n"<<endl;

Page 99: Data structure and algorithm All in One

• }• while(top!=11);• cout<<"stack full";• // pop operation• s[top]=NULL;• for(j=top; j>=1;j--)• cout<<s[j]<<endl;• }

Page 100: Data structure and algorithm All in One

Queue• A queue is a linear list of elements in which deletion can take

place only at one end, called the front, and insertions can take place only at the other end, called

• the rear. The term “front” and “rear” are used in describing a linear list only when it

• is implemented as a queue.• Queue is also called first-in-first-out (FIFO) lists. Since the

first element in a• queue will be the first element out of the queue. In other

words, the order in which• elements enters a queue is the order in which they leave.

Page 101: Data structure and algorithm All in One

• Primary queue operations:• Enqueue: insert an element at the rear of the

queue.• Dequeue: remove an element from the front

of the queue.

Page 102: Data structure and algorithm All in One
Page 103: Data structure and algorithm All in One
Page 104: Data structure and algorithm All in One

Insertion Algorithm in Queue

Page 105: Data structure and algorithm All in One
Page 106: Data structure and algorithm All in One
Page 107: Data structure and algorithm All in One

107

Deques• A deque is a double-ended queue• Insertions and deletions can occur at either

end• Implementation is similar to that for queues• Deques are not heavily used• You should know what a deque is, but we

won’t explore them much further