Professional Documents
Culture Documents
Data Structure and Algorithms
Data Structure and Algorithms
Algorithms
Teacher - Daw Theingi AyeWai Yan Thein
1 | Page
Structure.
Data
ADD
INSERT
DELETE or REMOVE
FIRST
NEXT
LAST
LOCATE
STACK
A LIST is a very general computer data structure. However, there are
certain type of the list that are so common, they are given their own
name. The STACK is a last-in First-Out (LIFO) list. Only the last item in
the stack can be accessed directly. If you had a number of items added
2 | Page
Structure.
Data
to a stack in this order 1.'Dog' 2.'Cat' 3.'Horse', the stack would look like
this
Cat
Adds an itemdog
to the
top
(first in)of the stack
Removes an item from the top of the stack
identifies the item at the top of the stack, but does not remove
it
QUEUE
The QUEUE is another extremely common type of list data structure.
A queue is a First-In, First-Out.
A queue maintains two pointers
1. A front of queue pointer
2. An end of queue pointer
Uses of a queue
A queue data structure is used whenever there are a number of items
waiting for a resource to become available. If you had three items added
3 | Page
Structure.
Data
to queue in the order 1.'Dog' 2.'Cat' 3.'Horse' the queue would look like
this
The start pointer locates 'dog' and the rear pointer locates 'horse'
Dog
Cat
Horse
Operations on a Queue
ADD
REMOVE
FRONT
remove it
Identifies the item at the front of the queue. but does not
remove it
TREE
4 | Page
Structure.
Data
The QUEUE and the STACK are linear lists. This mean each data item
only points to the one before it and after it. They have the idea of order
built into them, such as 'last' or 'first'. But they do not imply there is any
relationship between the data items themselves. The TREE on the other
hand, is designed to represent the relationship between data items
Just like a family tree, a TREE data structure is illustrated below
5 | Page
Structure.
Data
Root Node
Node at the "top" of a tree - the one from which all operations on the tree
commence. The root node may not exist (a NULL tree with no nodes in
it) or have 0, 1 or 2 children in a binary tree.
Leaf Node
Node at the "bottom" of a tree - farthest from the root. Leaf nodes have
no children.
Complete Tree
Tree in which each leaf is at the same distance from the root. A more
precise and formal definition of a complete tree is set out later.
Height
Number of nodes which must be traversed from the root to reach a leaf
of a tree.
6 | Page
Structure.
Data
The quick sort uses divide and conquer to gain the same advantages
as the merge sort, while not using additional storage. As a trade-off,
however, it is possible that the list may not be divided in half. When this
happens, we will see that performance is diminished.
A quick sort first selects a value, which is called the pivot value.
Although there are many different ways to choose the pivot value, we will
simply use the first item in the list. The role of the pivot value is to assist
with splitting the list. The actual position where the pivot value belongs in
the final sorted list, commonly called the split point, will be used to
divide the list for subsequent calls to the quick sort.
Figure 12 shows that 54 will serve as our first pivot value. Since we have
looked at this example a few times already, we know that 54 will
eventually end up in the position currently holding 31. The partition
process will happen next. It will find the split point and at the same time
move other items to the appropriate side of the list, either less than or
greater than the pivot value.
7 | Page
Structure.
Data
lower half of the list as well as the middle item can be eliminated from
further consideration. The item, if it is in the list, must be in the upper
half.
We can then repeat the process with the upper half. Start at the middle
item and compare it against what we are looking for. Again, we either
find it or split the list in half, therefore eliminating another large part of
our possible search space. Figure 3 shows how this algorithm can
quickly find the value 54. The complete function is shown in CodeLens 3.
8 | Page
Structure.
Data
9 | Page
Structure.
Data
i := i + 1;
}
return even .
Task 2
2.1 implement data structures in an executable programming
language in the context of well-defined problems
Searching
Linear Search
#include<iostream.h>
#include<conio.h>
int main()
{
10 | P a g e
Structure.
Data
int Arr[100],n,val,found;
cout<<"Enter number of elements you want to insert ";
cin>>n;
for(int i=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>Arr[i];
}
found=lsearch(Arr,n,val);
if(found==1)
cout<<"\nItem found";
else
cout<<"\nItem not found";
getch();
return 0;
}
11 | P a g e
Structure.
Data
Binary
Binary searching
#include<iostream.h>
#include<conio.h>
main()
{
12 | P a g e
Structure.
Data
int a[100],n,i,beg,end,mid,item;
beg=1;
end=n;
mid=(beg+end)/2;
13 | P a g e
Structure.
end=mid-1;
mid=(beg+end)/2;
}
if(a[mid]==item)
{
cout<<"\nData is Found at Location : "<<mid;
}
else
{
cout<<"Data is Not Found";
}
getch();
}
Data
14 | P a g e
Structure.
Data
Sorting
Heap Sort
# include <iostream.h>
# include <conio.h>
main()
{
int a[50],size;
int p,c,i;
cout<<"Enter the Size of an Array :";
cin>>size;
15 | P a g e
Structure.
Data
{
if( a[c] > a[p])
{
int t=a[c];
a[c]=a[p];
a[p]=t;
}
c=p;
p=p/2;
if(p<1)
{
break;
}
}
}
cout<<endl<<"Heap ..."<<endl;
for(i=1;i<=size;i++)
{
cout<<endl;
cout<<"Arr["<<i<<"] :"<<a[i];
}
int j=size;
int lc,rc;
while(j>1)
{
if(a[1] > a[j])
16 | P a g e
Structure.
Data
{
int t=a[1];
a[1]=a[j];
a[j]=t;
j--;
}
else
{
j--;
continue;
}
p=1;
while(p < j)
{
lc=p*2;
rc=p*2 + 1;
if(lc>=j || rc >=j)
{
break;
}
if(a[p] < a[lc] && a[lc] > a[rc])
{
int temp=a[lc];
a[lc]=a[p];
a[p]=temp;
p=lc;
17 | P a g e
Structure.
Data
}
else if (a[p] < a[rc] && a[rc] > a[lc])
{
int temp=a[rc];
a[rc]=a[p];
a[p]=temp;
p=rc;
}
else
{
break;
}
}
}
getch();
}
18 | P a g e
Structure.
Data
Quick Sort
#include <iostream.h>
#include <conio.h>
main()
{
void srt(int[],int,int);
int a[10],count=0,n;
19 | P a g e
Structure.
Data
n=0;
srt(a,n,count-1);
cout<<"\t\tThe Sorted order is : \n";
for (n=0;n<10;n++)
{
cout<<"\t\tposition : "<<(n+1)<<"\t"<<a[n]<<"\n";
}
getch();
}
void srt(int k[20],int lb,int ub)
{
int i,j,key,flag=0,temp;
if (lb<ub)
{
i=lb;
j=ub+1;
key=k[i];
while(flag!=1)
{
i++;
while(k[i]<key)
{
i++;
}
j--;
20 | P a g e
Structure.
Data
while(k[j]>key)
{
j--;
}
if (i<j)
{
temp=k[i];
k[i]=k[j];
k[j]=temp;
}
else
{
flag=1;
temp=k[lb];
k[lb]=k[j];
k[j]=temp;
}
}
srt(k,lb,j-1);
srt(k,j+1,ub);
}
}
21 | P a g e
Structure.
Data
22 | P a g e
Structure.
Data
Binary Search
1. Coding
#include<iostream.h>
#include<conio.h>
void search(int a[], int beg, int end, int item)
// Function to Search
Element
{
if(beg==end)
{
if(item==a[beg])
cout<<"\nThe Element is Found at Position : "<<beg;
else
cout<<"\nData is Not Found";
}
else
23 | P a g e
Structure.
Data
{
int mid = (beg + end)/2;
if(item == a[mid])
cout<<"\nThe Element is Found at Position : "<<mid;
else
search(a,mid+1,end,item);
}
main()
{
24 | P a g e
Structure.
Data
int a[100],item,n,beg,end,mid,loc;
cout<<"\n------- Binary Search using Recursion -------\n\n";
cout<<"Enter the number of Elements : ";
cin>>n;
beg=1;
end=n;
search(a,beg,end,item);
25 | P a g e
Structure.
Data
getch();
}
2. Interface
Error Handling
1. Undeclared Variables
int main()
{
cin>>x;
cout<<x;
}
"Huh? Why do I get an error?"
Your compiler doesn't know what x means. You need to declare it
as a variable.
int main()
{
26 | P a g e
Structure.
Data
int x;
cin>>x;
cout<<x;
}
2. Using a single equal sign to check equality
char x='Y';
while(x='Y')
{
//...
cout<<"Continue? (Y/N)";
cin>>x;
}
27 | P a g e
Structure.
Data
cin>>x;
}
3. Extra Semicolons
int x;
for(x=0; x<100; x++);
cout<<x;
28 | P a g e
Structure.
Data
int a, b;
int sum;
cout<<Enter two numbers to add: ;
cin>>b;
cin>>a;
sum=a+b;
cout<<The sum is: <<sum;
Remember! If you don't put " in necessary place you compiler will
keep saying Missing Terminating " Expected
int a, b;
int sum;
cout<<"Enter two numbers to add: ";
cin>>b;
cin>>a;
sum=a+b;
cout<<"The sum is: "<<sum;
29 | P a g e
Structure.
Data
cout<<x;}
Meaning of coding
#include <iostream>
#include <cstdlib>
using namespace std;
main()
{
int i,c;
cout<<"Enter Number!"<<endl; //Show "Enter
number" in command prompt//
cin>>i; //put user enter number into int i//
for(int l=2; l<=12; l++) //looping for 11 times untill l
reach 12//
{
if(i/l==0 ) //if int i divide int l equal 0
{
if(i!=2 && i!=3) //if int i not equal 2 and int i
not eqal 3 the program command line in ( } will work , if not
will go to next phase
{
cout<<"This number is not prime
number \n"; //show "This number is not prime number in
command prompt"
}
else //if first condition doesn't work out ,
else command line will excute
30 | P a g e
Structure.
Data
{
cout<<"this number is prime \n";
//show "Enter
}
}
else if(i/l!=0) //if first condition doesn't work out ,
int i divide int l == 0 condition will test
{
cout<<"This number is prime \n"; //show
"this number is prime in command prompt"
}
exit(0);
//exit
31 | P a g e
Structure.
Data
32 | P a g e
Structure.
Data
}
void show_data()
{
cout<<feet<<" feet "<<inches<<" inches "<<endl;
}
};
main()
{
distances dd,ee,ff,temp2;
dd.get_data();
ee.get_data();
temp2 = ff.add_data(dd,ee);
temp2.show_data();
}
Interface of a program
Task 3
33 | P a g e
Structure.
Data
I.
Example Coding
#include <iostream>
#include <cstring>
#include <string>
int main ()
{
std::string str ("Hit me into pieces");
34 | P a g e
Structure.
Data
delete[] cstr;
return 0;
}
II.
Interface
String :: copy
Copies a substring of the current value of the string object into the array
pointed by s. This substring contains the len characters that tart at
position pos.
This function does not append a null character at the end of the copied
content
s
len
pos
postion
I.
Example Coding
#include <iostream>
#include <string>
35 | P a g e
Structure.
Data
int main ()
{
char buffer[20];
std::string str ("Test string...");
std::size_t length = str.copy(buffer,6,5);
buffer[length]='\0';
std::cout << "buffer contains: " << buffer << '\n';
return 0;
}
II.
Interface
string: find
Searches the string for the first occurrence of the sequence specified by
its arguments. When pos is specified, the search only includes
characters at or after position pos, ignoring any possible occurrences
that include characters before pos. Notice that unlike member
find_first_of, whenever more than one character is being searched for, it
is not enough that just one of these characters match, but the entire
sequence must match.
Parameter
str
pos
36 | P a g e
Structure.
Data
Example Coding
#include <iostream>
#include <string>
int main ()
{
std::string str ("There are two nouns in this sentence with nouns.");
std::string str2 ("noun");
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'noun' found at: " << found << '\n';
37 | P a g e
Structure.
Data
found=str.find("sentence");
if (found!=std::string::npos)
std::cout << "'sentence' also found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
str.replace(str.find(str2),str2.length(),"preposition");
std::cout << str << '\n';
return 0;
}
II.
Interface
String :: rfind
Searches the string for the last occurrence of the sequence specified by
its arguments. When pos is specified, the search only included
sequences of characters that begin at or before position pos, ignoring
any possible match beginning after pos
38 | P a g e
Structure.
Data
Str
pos
I.
Example Coding
#include <iostream>
#include <string>
int main ()
{
std::string str ("I Hate You !");
std::string key ("Hate");
39 | P a g e
Structure.
Data
return 0;
}
II.
Interface
String :: find_first_of
Searches the string for the first character that matches any of the
characters specified in its arguments. When pos is specified, the search
only includes characters at or after position pos, ignoring any possible
occurrences before pos. Notice that it is enough for one single character
of the sequence to match (not all of them). See string::find for a function
that matches entire sequences.
Parameters
Str
Pos
40 | P a g e
Structure.
Data
I.
Example Coding
#include <iostream>
#include <string>
#include <cstddef>
int main ()
{
std::string str ("The vowels in this sentense gonna replace by
asterisks.");
std::size_t found = str.find_first_of("aeiou");
while (found!=std::string::npos)
{
str[found]='*';
found=str.find_first_of("aeiou",found+1);
}
return 0;
}
41 | P a g e
Structure.
II.
Data
Interface
String :: substr
Returns a newly constructed string object with its value initialized to a
copy of a substring of this object. The substring is the portion of the
object that starts at character position pos and spans len characters (or
until the end of the string, whichever comes first).
Parameters
pos
len
I.
Example Coding
#include <iostream>
#include <string>
42 | P a g e
Structure.
Data
int main ()
{
std::string str="We think in generalities, but we live in details.";
return 0;
}
II.
Interface
Task 4
3.2 demonstrate the outcome of string operations in specified
algorithm
Outcome of a string operation
I.
Example Code
#include<stdio.h>
#include<conio.h>
43 | P a g e
Structure.
Data
44 | P a g e
Structure.
else
printf("Entered strings are not equal.\n");
return 0;
}
int string_ln(char*p) /* p=&str[0] */
{
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
int compare_string(char *first, char *second)
{
while(*first==*second)
{
if ( *first == '\0' || *second == '\0' )
break;
first++;
second++;
}
if( *first == '\0' && *second == '\0' )
return 0;
Data
45 | P a g e
Structure.
else
return -1;
}
II.
Data