Data structure and algorithm All in One
Transcript of Data structure and algorithm All in One
Data Structure and Algorithm
Prepared by Basharat JehanEmail: [email protected]
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.
• 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
• 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.
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:
• 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.
Field, Record and File
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.
Algorithm Notations
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.
ALGORITHM
INTRODUCTION
• An algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function
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)
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
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.
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.
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.
The flow diagram of the minimum finding problem
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:
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.
FINDING LENGTH OF ARRY
• MAXIMUM LENGTH= UPPER BOUND(UB)-LOWER BOUND(LB)+1
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,…………
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.
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.
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
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();}
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
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();• }
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
representing 2D array in memory
Inserting
• Inserting: Adding a new record to the end of array.
• Insertion may be at end of array or at specific location.
• 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
• #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();
• }
Element insertion at specific location
• Algorithm to insert element in array requires the specific location at which the element is to be added.
• 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.
• #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;• }
• 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);• }
Useful link
• http://www.enjoylearningcs.com/array-operation-insert-delete-element/
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.
Algorithm to Delete Element from Array is:
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
• 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
•
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.
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.
59
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),
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;• }•
• int Fibonacci(int n)• {• if ( n == 0 )• return 0;• else if ( n == 1 )• return 1;• else• return ( Fibonacci(n-1) + Fibonacci(n-2) );• }
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”
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.
• 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
• 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)
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]
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;
• for (i=1; i<=n; i++)• {• cin>>A[i];• }• cout<<"item to be searched";• cin>>ITEM;
• i=0;• while(i<=n)• {• if (ITEM==A[i]){• LOC=i;• cout<<"location"<<LOC;• }• i++;• }
• if(LOC==-1)• {•• cout<<"data not found";• }• }
• Can only be performed on a sorted list !!!
• Uses divide and conquer technique to search list
Binary Search Algorithm
• 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)
• 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]
Binary Search Algorithm (Cont’d)
Figure 4: Search list, list[6] … list[11]
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;• }•
• cout<<"enter item to be searched "<<endl;• cin>>item;• int middle=(1+n)/2;• cout<<middle;• if(item==a[middle])• {• cout<<middle;• }
• if(item>a[middle])• {• i=middle+1;• while(i<=n)• {• if(item==a[i])• {• Loc=i;• cout<<loc;• }• i++;• }}•
• 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";• }• }
Sorting
• Definition is discussed already in previous slides.. See data structure operations types
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.
• 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.
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];• }•
• 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];• }•• }
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.
example
algorithm
See example animated example at
• http://courses.cs.vt.edu/csonline/Algorithms/Lessons/InsertionCardSort/insertioncardsort.swf
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).
• 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.
• 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.
Stack push and pop program
• #include<iostream>• #include<conio.h>• using namespace std;• main()• {• int s[10], i,j,n;
• int top=0;
• 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;
• }• while(top!=11);• cout<<"stack full";• // pop operation• s[top]=NULL;• for(j=top; j>=1;j--)• cout<<s[j]<<endl;• }
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.
• Primary queue operations:• Enqueue: insert an element at the rear of the
queue.• Dequeue: remove an element from the front
of the queue.
Insertion Algorithm in Queue
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