Series of articles written by me for Vidusara Science Magazine, Sri Lanka [2012]; sharing for all those who like to learn the basics of Data Structures and Algorithms in Sinhala.
2. Data Structures සරලව පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
මේ ලිපිමඳළින් මා බාමඳොරාත්තු ලන්මන්, Data
Structures & Algorithms ගැන ඔබට ගැන වරල
කියාමදන්නයි. මෘදුකාාංග නිර්මාණයට අදාෂ තලත්
ලැදගත් විය ඳථයක් තමයි ඒ......
OOP ලිපිමඳෂ මගමනන විට, 24 ලන ලිපිමේ මම
වශන් කෂා, Data Structures & Algorithms
ගැන ඔබට ගැන වරල අදශවක් බාමදන්නේ
කියා....ඒ මඳොමරොන්දුල ඉ්ට කරන්නයි මේ
සූදානම.
දත්ත නිසියාකාරල කෂමනාකරණය කර ගැනීමට
Data Structures & Algorithms අලය මලනලා...
මෘදුකාාංග ක්මේව්ත්රමේ ඉතා වර application එමක්
සිට වාංකීර්ණ එක දක්ලා, ඒලාමේ ක්රියාකාත්ත්ලය
තියුණු කරගැනීමට විවිධ මව Data Structures &
Algorithms භාවිතමලනලා......
මුලින්ම අපි, Data Structures ගැන වරල කතා
කරමු. වරලම කිව්මලොත්, Data Structures
කියන්මන් දත්ත අසුරණ ක්රමමව්දයන්ටයි. (Data
Structures are a way of organizing data in the
computer’s memory)
ප්රධාන ලමයන් මකොටව් මදකකට මබමදනලා.
1. Linear Data Structures
a. Ordered List
b. Stack
c. Queue
2. Non Linear Data Structures
a. Multidimensional arrays
b. Trees
c. Graphs
Note: මීට අමතරල අපි Linear Data Structures
"Abstract Data Types" මවද ශඳුන්ලනලා...
ඔබ normal data types ගැන දන්නලා...(Integer,
String, Char, Boolean...) ඒ ලමේම අපි List, Stack
වශ Queue යන Linear Data Structures ද data
types මව වැකුලත් ඒලාමේ විමේත්ලය නේ,
ඒලාට වේබන්ධ කරුණු මදකක් තිබීමයි.
1) Values 2) Operations
පහත රූප සටහන බලේන:
List (Abstract View):
Stack (Abstract View):
Queue (Abstract View):
Mulitidimensional Arrays (Abstract View):
Trees (Abstract View):
Graphs (Abstract View):
නේ එක එකක් data structures ගැන සහ ඒවානේ
implementations මම මීළඟ ලිපි වලිේ ඔබට
නගන එේනේ!
Reference: Some internet sources – for the pictures
3. Data Structures සරල.... ඳරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
Linear Data Structures – Part 1 : Linked List
අපි අද කතා කරේනේ මූලිකම Data Structure
එකක් ලන Singly Linked List ගැනයි.
Linked list is the most basic data structure that
we have to study. First, we need to study
singly linked lists.
Singly linked list එකක් හැදී ඇත්නත් එකිනනක
සම්බේධ වූ nodes ලලිනි. නම් node එකක, ඊට
අදාළ දත්තයද, අනනක් එනක් memory address
එකද අඩංගු නලනලා. List එක අලසේ ලේනේ
ඊළඟ (next) node එක කිසිඳු node එකකට
සම්බේධ නනොලන විටයි.(does not point to
another node) ඉහත රූඳ සටහන නහොඳිේ බේන.
A linked list is a simple chain of nodes where a
node points to next node till the next node
doesn't point to anything.
A node is a simple object which contains some
data and a reference to next node.
Normal List Operations:
1. Add elements (nodes) to a list
2. Delete an element(node) from a list
3. Search an element(node) of a list
4. Count the number of elements of a list
5. Print the contents of a list
Note:නම් ලිපි නඳනළේ අපි C++ සහ C# යන භාෂා නදනකේම
Data Structures නගොඩනගන හැටි අධ්යනය කරමු!
Sample List Operations නඳේනුම් කරන C++ codes මම අද
ඔබට නගන එේනම්.
Note: ඔබට මතක නම්, විදුසර හරහා මම C programming ලිපි
නඳළක් නගන අලා...එහි pointers ගැන ලිපි කීඳයක් තිබුනා...ඒ
සංකල්ඳයම C++ ලදීත් භාවිතා කරනලා, නම් Data Structures
නගොඩ නැගීමට!
1. Create a Node
class Node {
Node* pnext;
public:
int data;
// Constructor taking initial value:
Node( int value = 0 ): pnext( NULL
), data( value )
{
}
};
2. Insert a node
void insert( Node* newNode )
{
newNode->pnext = pnext;
pnext = newNode;
}
3. Delete a node
void removeNext()
{
if ( pnext == NULL ) return;
Node* obsolete = pnext;
this->pnext = obsolete->pnext;
// Make node "single":
obsolete->pnext = NULL;
}
4. Distance between nodes(searching
should be there) and List size
int distance( Node const* other )
const
{
int hops = 1;
Node const* iter = pnext;
while ( iter != other ) {
if ( iter == NULL )
return hops - 1;
iter = iter->pnext;
++hops;
}
return hops;
}
// Calculate number of nodes in
the list:
size_t size() const
{
return distance( NULL );
}
5. Print the elements in the list
void printList( Node const& head )
{
cout << '[' << head.size() << "] ";
Node const* iter = &head;
do {
cout << iter->data << ' ';
iter = iter->pnext;
} while ( iter != NULL );
cout << 'n';
}
නම් සියල් එකට නකොට ලැඩක් ගැනීම සහා ඳහත
main function එක ලිවිය හැකිය:
int main ( )
{
Node A;
Node B;
Node C;
Node D;
//Initialize data of the 3 nodes:
A.data = 10;
B.data = 20;
C.data = 30;
D.data = 40;
//Insert the needed elements to the
list:
A.insert( &C );
A.insert( &B );
A.insert( &D);
//Print the current content of the list:
cout<<"Current list elements:n";
printList(A);
//Print the current List size:
cout << "List size is: " <<
A.size();
//Remove an element from the list:
A.removeNext();
//Print the current content of the list:
cout<<"Current list elements:n";
printList(A);
//Print the current List size:
cout << "List size is: " <<
A.size();
return 0;
}
බන සතිනේ අපි C++ ල inbuilt ‘list’ header file එක
නයොදා නගන list operations කරන ආකාරයත් C# ලලිේ
list operations කරන ආකාරයත් කතා කරමු!
4. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Linear Data Structures – Part 1 : Linked List
(Contd.)
අද මුලින්ම අපි අවධානය යයොමු කරන්යන් C++ වල
inbuilt, list header file එක යයොදායෙන linked list
operations කරන අකාරයටයි...
පහත program එක යහොඳින් අධයනය කරන්න:
#include <iostream>
#include <list>
using namespace std;
int main ()
{
//Integer list having 3
elements of value 50
list< int > mylist( 3, 50);
//Print the current contents:
cout << "My original list
contains:";
list<int>::iterator i;
for ( i = mylist.begin(); i !=
mylist.end(); ++i )
{
cout << " " << *i;
}
cout << endl;
//Add elements in front:
mylist.push_front( 20 );
mylist.push_front( 10 );
//Add elements at back:
mylist.push_back( 70 );
//Print the current contents:
cout << "My new list after
inserting:";
list<int>::iterator j;
for ( j = mylist.begin(); j !=
mylist.end(); ++j )
{
cout << " " << *j;
}
cout << endl;
//Delete an element in front
mylist.pop_front();
//Print the current contents:
cout << "My new list after
deleting:";
list<int>::iterator k;
for ( k = mylist.begin(); k !=
mylist.end(); ++k )
{
cout << " " << *k;
}
cout << endl;
return 0;
}
යමහිදී,මුලින්ම value එක 50 වන elements/nodes 3ක list
එකක් declare කර ඊට nodes add, delete කර elements print
කරන අයුරු දක්වා තියෙනවා. යේ සඳහා push_front සහ
pop_front නමැති predefined methods භාවිතා කර
තියෙනවා..List එයක් ඉදිරියට node එකක් දැමීම සහ ඉවත්
කිරීම යමමගින් සිදුයකයරනවා.
දැන් අපි ෙලමු C# වල generics (List<T>) භාවිතා
කරලා List Operations කරෙන්යන් යකොයහොමද
කියලා....පහත program එක යහොඳින් අධයනය
කරන්න:
Person.cs
using System;
using System.Collections.Generic;
namespace ListOperations
{
class Person
{
public Person()
{
}
public Person(int id, string
first_name, string last_name, short age,
char sex)
{
this.p_id = id;
this.first_name = first_name;
this.last_name = last_name;
this.p_age = age;
this.p_sex = sex;
}
private int p_id = -1;
private string first_name =
String.Empty;
private string last_name =
String.Empty;
private short p_age = 0;
private char? p_sex = null;
public int ID
{
get
{
return p_id;
}
set
{
p_id = value;
}
}
public string FirstName
{
get
{
return first_name;
}
set
{
first_name = value;
}
}
public string LastName
{
get
{
return last_name;
}
set
{
last_name = value;
}
}
public short Age
{
get
{
return p_age;
}
set
{
p_age = value;
}
}
public char? Sex
{
get
{
return p_sex;
}
set
{
p_sex = value;
}
}
//Print method
public static void
PrintOnConsole(List<Person> pList, string
info)
{
Console.WriteLine(info);
Console.WriteLine("n{0,2} {1,8}
{2,8} {3,2} {4,2} ",
"ID", "FName", "LName",
"Age", "Sex");
pList.ForEach(delegate(Person
per)
{
Console.WriteLine("{0,2}
{1,8} {2,10} {3,2} {4,2} ",
per.ID, per.FirstName,
per.LastName, per.Age, per.Sex);
});
Console.ReadLine();
}
}
}
Program.cs
using System;
using System.Collections.Generic;
namespace ListOperations
{
class Program
{
static void Main(string[] args)
{
//Declare the list:
List<Person> pList = new
List<Person>();
//Add 4 elements:
pList.Add(new Person(1,
"Tharindu", "Weerasinghe", 29, 'M'));
pList.Add(new Person(2,
"Rajendra", "Dissanayake", 50, 'M'));
pList.Add(new Person(3,
"Sunimali", "Weerasinghe",45, 'F'));
pList.Add(new Person(4,
"Samanali", "Jayasooriya", 28, 'F'));
//Print the contents:
Person.PrintOnConsole(pList,
"--- Printing all elements in the list -
--");
//Delete Male Employees and
print the remaining contents:
List<Person> removeList =
pList;
removeList.RemoveAll(delegate(Person p)
{ return p.Sex == 'M'; });
Person.PrintOnConsole(removeList, "---
Remove male employees from List<> ---");
}
}
}
5. Data Structures සරල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
Linear Data Structures – Part 2 : Stack
අද අප අලධානය නයොමු කරේනේ Linear Data
Structures ල නදනලනි ලර්ගය ලන ‘Stack’
ගැනයි.
අද අපි මුලිේම Stack operations ගැන කතා කර
පසුල C++ ලලිේ program කරන අයුරු හදාරමු.
Stack operations, සරල LIFO (Last In – First Out)
නස හැඳිේවිය හැකිය. එය පැහැදිලි කනළොත්, මුලිේම
insert කරන element එක තමයි අේතිමට එළියට ගේන
නලේනේ!
Stack එකක් ආකාර නදකකිේ implement කළ
හැකිය. එකක්, arrays භාවිතා කර සහ අනනක,
linked list භාවිතා කර.....
Stack operations ලදී න ොනහෝවිට අපි push (to
insert elements to the stack) සහ pop (to pick the
topmost element of the stack) යන methods
භාවිතා කරනලා...
මුලිේම අපි මු C++ ල array based stack
implementation එකක්:
Operations
Stack create()
creates empty stack
boolean isEmpty(Stack s)
tells whether the stack s is empty
push(Stack s, Item e)
put e on top of the stack s
Item peek(Stack s)
returns topmost element in stack s
Precondition: s is not empty
pop(Stack s)
removes topmost element from the stack s
Precondition: s is not empty
destroy(Stack s)
destroys stack s
#include<conio.h>
#include<stdio.h>
class Stack {
private:
int top, capacity, *storage;
public:
Stack(int capacity) {
if (capacity <= 0)
printf("nStack's capacity
must be positive!");
storage = new int[capacity];
this->capacity = capacity;
top = -1;
}
void push(int value) {
if (top == capacity)
printf("nStack's underlying
storage is overflow!");
top++;
storage[top] = value;
}
int peek() {
if (top == -1)
printf("nStack is empty!");
return storage[top];
}
void pop() {
if (top == -1)
printf("nStack is empty!");
top--;
}
bool isEmpty() {
return (top == -1);
}
~Stack() {
delete[] storage;
}
};
Singly linked list based stack implementation:
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *link;
} *top = NULL, *temp;
void main()
{
int choice,data;
while(1)//Infinite loop is used to
insert/delete infinite number of nodes
{
printf("n1.Pushn2.Popn3.Displayn4.Ex
itnn");
printf("nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
temp=(struct node
*)malloc(sizeof(struct node));
printf("Enter your element:
");
scanf("%d",&data);
temp->data=data;
temp->link=top;
top=temp;
break;
case 2:
if(top!=NULL)
{
printf("The poped
element is %d",top->data);
top=top->link;
}
else
{
printf("nStack
Underflow");
}
break;
case 3:
temp=top;
if(temp==NULL)
{
printf("nStack is
empty!n");
}
while(temp!=NULL)
{
printf("->%d->",temp-
>data);
temp=temp->link;
}
break;
case 4:
exit(0);
}
}
}
Next Week: Stack implementations in C#
6. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Linear Data Structures – Part 2 : Stack
(Contd.)
අද අප අවධානය නයොමු කරේනේ C# වලිේ නකනරන
Stack implementation එකක් නදසයි.
අපි බලමු Linked List based Stack එකක් C# වලිේ
නගොඩනගන හැටි:
1. Node එකක් define කරන Node class එක:
(Node.cs)
//Sample linked list Node
implementation
public class Node
{
public string Data {get; set;}
public Node Next {get; set;}
public Node(string d)
{
this.Data = d;
}
}
2. Stack එක implement කරන Stack class එක:
(Stack.cs)
//Stack implementation using linked
list with standard operations - Push,
Pop, Clear, Search of Integers
using System;
using System.Text;
public class Stack
{
private Node top = null;
Boolean flag = false;
public void Push(String obj)
{
Node newNode = new Node(obj);
if (top == null)
top = newNode;
else
{
Node temp = top;
top = newNode;
top.Next = temp;
}
}
public string Pop()
{
if (top == null)
{
Console.WriteLine("Stack
is empty!n");
return null;
}
else
{
Node objToPop = top;
top = top.Next;
return objToPop.Data;
}
}
public void Search(String obj)
{
if (top == null)
Console.WriteLine("Stack is
empty!n");
else
{
do{
if (top.Data == obj)
{
flag = true;
break;
}
else
flag = false;
top = top.Next;
} while (top != null);
if (flag)
Console.WriteLine("Element Found!n");
else
Console.WriteLine("Element Not
Found!n");
}
}
public void Display()
{
if (top == null)
Console.WriteLine("No
elements, stack is empty!n");
else
{
do{
Console.WriteLine(top.Data);
top = top.Next;
} while (top != null);
Console.WriteLine("n");
}
}
}
3. නේ classes නදනකේ වැඩක් ගේන, main method
එක ඇති Program.cs එක:
using System;
using System.Text;
namespace StackOperations
{
class Program
{
static void Main(string[] args)
{
string choice, element;
Stack myStack = new
Stack();
Console.WriteLine("nStack
Operations Demo - Stack is having
Strings");
Console.WriteLine("====================
============================n");
while (true)
{
Console.WriteLine("Menu:");
Console.WriteLine("----
-");
Console.WriteLine("1.Pushn2.Popn3.Sea
rchn4.Displayn5.Exitn");
Console.WriteLine("Enter
your choice: ");
choice =
Console.ReadLine();
Console.WriteLine("n");
switch (choice)
{
case "1":
Console.WriteLine("Enter your element:
");
element =
Console.ReadLine();
myStack.Push(element);
Console.WriteLine("n");
break;
case "2":
element =
myStack.Pop();
if (element !=
null)
Console.WriteLine("Popped element: " +
element + "n");
break;
case "3":
Console.WriteLine("Enter an element to
be searched: ");
element =
Console.ReadLine();
myStack.Search(element);
Console.WriteLine("n");
break;
case "4":
Console.WriteLine("Current elements of
the stack: ");
myStack.Display();
break;
case "5":
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid Input!n");
break;
}
}
}
}
}
Sample Output:
7. Data Structures සරල.... ඳරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
Linear Data Structures – Part 3 : Queue
අද අඳ අලධානය නයොමු කරේනේ Linear Data
Structures ල ඊළඟ ලර්ගය ලන „Queue‟ ගැනයි.
අද අපි මුලිේම Queue operations ගැන කතා කර
ඳසුල C++ ලලිේ program කරන අයුරු හදාරමු.
Queue operations, “First In First Out (FIFO)” යන
සංකල්ඳය යටනේ elements insert (enqueue), delete
(dequeue) කිරීම සිද්ධ නලයි. සරල කිව්නලොේ, මුලිේ
ඇතුේ කරන element එක මුලිේම එලියට ගේන
නලනලා....
Stack එක ලනේම Queue එකකේ Singly Linked List
based implementation එක තමයි නහොම ක්රඑමය
Queue operations program කරේනට.....
මා අේතර්ජානයේ නසොයාගේ ඳහත රඳ සටහේ ඔබට
enqueue සහ dequeue operations මානල ඳැහැදිලි
කරාවී….
C++ Coding: (Linked List Based “Queue” implementation)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
} *head = NULL, *tail = NULL, *temp;
void free();
void main()
{
int choice,data;
while(1)
{
printf("nQueue Operations - Menu");
printf("n========================");
printf("n1.Enqueuen2.Dequeuen3.Display
n4.Exitnn");
printf("nEnter your choice: ");
scanf("%d",&choice);
printf("n");
switch(choice)
{
case 1:
temp = (struct node
*)malloc(sizeof(struct node));
printf("Enter your element: ");
scanf("%d",&data);
temp->data=data;
temp->next=NULL;
tail->next=temp;
tail = temp;
break;
case 2:
if(head!=NULL)
{
data = head->data;
temp = head;
head = head->next;
free();
printf("nThe poped
element is %d",data);
printf("n");
}
else
{
printf("Queue Underflown");
}
break;
case 3:
temp=head;
if(temp==NULL)
{
printf("Queue is empty!n");
}
while(temp!=NULL)
{
printf("->%d->",temp->data);
temp=temp->next;
}
break;
case 4:
exit(0);
break;
default:
printf("nEnter a vaild
input");
break;
}
}
}
//To free the head node when dequeuing
void free()
{
node *temp;
while(head!=NULL)
{
temp = head;
delete head;
head =temp->next;
}
}
8. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Linear Data Structures – Part 3 : Queue
(Contd.)
පසුගිය සතිනේ අපි C++ වලිේ queue
implementation එකක් කරන අයුරු
දැනගත්තා.....නේ සතිනේ අපි C# වලිේ queue
implementation එකක් කරන අයුරු හදාරමු....
පහත නෝtග්රෑකේ එක අයයනය කරේන.. නෙහිදී කිසඳු
generic data structures එකක් නයොදා
නනොනගනයි නෝtග්රෑකේ එක ලියා තිනෙේනේ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QueueImplementation
{
using System;
public class Queue
{
private uint count = 0;
private Node front = null;
private Node end = null;
private Node temp = null;
/*Test to see if the Queue
might be empty.*/
public bool empty
{
get
{
return (count ==
0);
}
}
/*Get the Number of Items
in the Queue.*/
public uint Count
{
get
{
return count;
}
}
/*This function will do the
enqueue operation */
public void enqueue(object
obj)
{
if (count == 0)
{
front = end = new
Node(obj, front);
}
else
{
end.Next = new
Node(obj, end.Next);
end = end.Next;
}
count++;
}
/*This function will do the
dequeue operation */
public object dequeue()
{
temp = front;
if (count == 0)
throw new
Exception("tried to dequeue from an
empty Queue");
front = front.Next;
count--;
return temp.Value;
}
/*This function will print
everything that is currently in the
queue*/
public void printQueue()
{
temp = front;
while (temp != null)
{
Console.WriteLine("{0}",
temp.Value.ToString());
temp = temp.Next;
}
}
}
/*The Node class holds the
object and a pointer to the next
Node class.*/
class Node
{
public Node Next;
public object Value;
public Node(object value,
Node next)
{
Next = next;
Value = value;
}
}
/* This function will test the
functionality of the Queue.*/
class QueueTest
{
static void Main()
{
Queue Q = new Queue();
object obj;
uint i, j;
UInt16[] numbers = new
UInt16[] { 10, 20, 30 };
for (i = 0; i <
numbers.Length; i++)
Q.enqueue(numbers[i]);
Q.printQueue();
Console.WriteLine("Queue
count = {0}", Q.Count);
j = Q.Count;
for (i = 0; i < j; i++)
{
obj = Q.dequeue();
Console.WriteLine("Dequeue Queue =
{0}", obj.ToString());
}
Console.WriteLine("Queue
count = {0}", Q.Count);
Console.ReadKey();
}
}
}
Output:
දැේ අපි ෙලමු C# generics භාවිතා කර පංචි නෝtග්රෑකේ
එකක් ලියන ආකාරය (queue එකක් හදේනට):
using System;
using System.Collections.Generic;
namespace QueueImplementation
{
class Program
{
static void Main(string[] args)
{
//Generic Queue of string
data type
Queue<string>
genericStringQueue = new
Queue<string>();
//Enqueue Data in the
Generic Queue
genericStringQueue.Enqueue("THARINDU");
genericStringQueue.Enqueue("tharindu@sam
ple.com");
genericStringQueue.Enqueue("Software
Engineer");
Console.WriteLine("Queue
count = " + genericStringQueue.Count +
"n");
//Dequeue Data from the
Generic Queue
Console.WriteLine(genericStringQueue.Deq
ueue());
Console.WriteLine(genericStringQueue.Deq
ueue());
Console.WriteLine(genericStringQueue.Deq
ueue());
Console.WriteLine("nQueue
count = " + genericStringQueue.Count +
"n");
Console.ReadKey();
}
}
}
9. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Linear Data Structures – Part 4 :
Binary Search Tree
අද සට අපි අවධානය නයොමු කරේනේ, තරමක්
සංකීර්ණ Data Structure එකක් වන Binary
Search Tree ගැනයි. මුලිේම අපි BST එකක
insert සහ search (in-order traversal)
operations නිරූපනය කරන C/C++ code
එකක් අධrනය කර පුවව න ස නේධ
සද්ධාේත ගැන කතා කරමු.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
//This program will demo the insert
and search(in-order) operations of a
BST
struct BST
{
int data;
struct BST *rChild, *lChild;
}*root, *newNode;
struct BST *search(int searchData)
{
struct BST *prev, *next;
next = root;
while(next != NULL)
{
if(searchData > next->data)
{
prev = next;
next = next->rChild;
}
else if (searchData < next-
>data)
{
prev = next;
next = next->lChild;
}
else
{
next = NULL;
prev = NULL;
}
}
return prev;
}
void insert()
{
struct BST *prev, *next;
newNode = (struct
BST*)malloc(sizeof(struct BST));
printf("nnInsert your element:
");
scanf("%d", &newNode->data);
if (root == NULL)
{
root = newNode;
root->rChild = NULL;
root->lChild = NULL;
}
prev = search(newNode->data);
if (prev)
{
if (newNode->data > prev->data)
prev->rChild = newNode;
else
prev->lChild = newNode;
next = newNode;
next->rChild = NULL;
next->lChild = NULL;
}
}
int main()
{
int srchData;
struct BST *flag;
printf("*************** DEMO TREE
OPERATIONS 1.0 ***************n");
printf("INSERT 5 Elements &
SEARCHn");
for (int i = 0; i<5; i++)
insert();
printf("nnEnter integer to search:
");
scanf("%d", &srchData);
flag = search(srchData);
if (flag)
{
printf("nnElement found!");
}
else
{
printf("nnElement not found!");
}
return 0;
}
To be Continued in the next week!
10. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Linear Data Structures – Part 4 : (Contd.)
Binary Search Tree/ Binary Sorted Tree
Binary Search Tree
General features:
Value of the right side node > Value of the
parent node (i.e.the root of that right
node)
Value of the left side node < Value of the
parent node (i.e. the root of that left
node)
Searching can be done by any of order
traversals
Used for:
Sorting
Searching
Constructing advanced data structures
like Sets
අපි, සරලව in-order traversal එක අයත් වන tree
traversal ගැන මුලින්ම කතා කරමු.
1. Preorder traversal
2. Post order traversal
3. Inorder traversal
ඉහතින් පෙන්වා ඇති BST එපේ අපි ඉහත
traversals 3 කර බලමු:
Preorder traversal:
1. Visit the root first; and then
2. Traverse the left subtree; and then
3. Traverse the right subtree.
Example according to the above tree:
4, 3,2,1,8,6,5,7,9
Postorder traversal:
1. Traverse the left subtree; and then
2. traverse the right subtree; and then
3. Visit the root.
Example according to the above tree:
1,2,3,5,6,8,7,9,4
Inorder traversal:
1. Traverse the left subtree; and then
2. Visit the root; and then
3. Traverse the right subtree.
Example according to the above tree:
1,2,3,4,5,6,7,8,9
තවත් උදාහරණයේ බලමු:
Preorder:
A,B,C,D,E,F,G,H,I
Postorder:
C,B,F,G,E,I,H,D,A
Inorder:
B,C,A,F,E,G,D,I,H
දැේ අපි බලමු preorder traversal එකක් C++ වලිේ
ලියන ආකාරයක්: Initially the flags of all nodes are
false. We set the flag of a node to be true once we
have traversed it.
struct Node {
int data;
Node *left;
Node *right;
Node *parent;
bool flag; };
void preorder ( Node *root)
{
Node *temp = root;
if (root == (Node*) NULL)
return;
while (true)
{
if (temp->flag == false)
{
//print its data
cout << temp->data
<<endl;
temp -> flag = true;
}
//make temp->left the new temp (if
temp->left is not null, and its flag is
false)
if (temp->left && !(temp-
>left->flag))
temp = temp->left;
else if (temp->right &&
!(temp->right->flag))
//if temp->left is
null, then make temp->right the new temp
(if temp->right is not //null, and its
flag is false).
temp = temp -> right;
else if (temp == root)
//we are done with
traversing all
nodes.
break;
else
// we are done
exploring all nodes in
subtree rooted at temp.
// make temp->parent
the new temp.
temp = temp -> parent;
}
}
To be Continued in the next week!
11. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
Linear Data Structures – Part 4 : BST
(Contd.)
Read the following codes with comments
carefully! (C++ implementation of a BST search
and insertion)
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
/*An object of type TreeNode represents
one node in a binary tree of strings.*/
struct TreeNode
{
char item; /*Data in this
node*/
TreeNode *left; /*Pointer to left
subtree.*/
TreeNode *right; /*Pointer to
right subtree.*/
//Constructor.
TreeNode(char str)
{
item = str;
left = NULL;
right = NULL;
}
}*root=NULL;
/*Recursive method to search an item
in the BST*/
bool treeContains(TreeNode *root, char
item)
{
/*Return TRUE if item is one of
the items in the binary sort tree to
which root points. Return false if
not.*/
if ( root == NULL )
{
/*Tree is empty, so it
certainly doesn't contain item.*/
return false;
}
else if ( item == root->item )
{
/*Yes, the item has been found
in the root node.*/
return true;
}
else if ( item < root->item ) {
/*If the item occurs, it must be in the
left subtree.*/
return treeContains( root-
>left, item );
}
else
{
/*If the item occurs, it must
be in the right subtree.*/
return treeContains( root-
>right, item );
}
}
/*Simple non-recursive method to
search an item in the BST*/
bool treeContainsNR(TreeNode *root,
char item)
{
/*Return true if item is one of the
items in the binary sort tree to which
root points. Return false if not.*/
TreeNode *runner; /*For "running"
down the tree.*/
runner = root; /*Start at the root
node.*/
while (true)
{
if (runner == NULL)
{
/*We've fallen off the
tree without finding item.*/
return false;
}
else if (item == runner->item)
{
// We've found the
item.
return true;
}
else if (item < runner->item)
{
/*If the item occurs,
it must be in the left subtree. So,
advance the runner down one level to the
left.*/
runner = runner->left;
}
else
{
/*If the item occurs, it must
be in the right subtree.*/
// So, advance the runner down
one level to the right.
runner = runner->right;
}
}
}
/*Recursive method to insert an
item to the BST*/
void treeInsert(TreeNode *&root,
char newItem)
{
/*Add the item to the binary sort
tree to which the parameter "root" refers.
Note that root is passed by reference
since its value can change in the case
where the tree is empty.*/
if (root == NULL)
{
/*The tree is empty. Set
root to point to a new node containing
the new item. This becomes the
only node in the tree.*/
root = new TreeNode(newItem);
/*NOTE: The left and right
subtrees of root are automatically set to
NULL by the constructor.This is
important!*/
return;
}
else if (newItem < root-
>item)
{
treeInsert( root->left,
newItem );
}
else
{
treeInsert( root->right,
newItem );
}
}
ඉහත දක්වා ඇත්නත් BST එකක search සහ
insertion operations සඳහා න ොදාගත
හැකි methods නදකක්.....ඒවා main program
එකක න ොදාගත හැකි ….
12. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Non linear Data Structures – Part 2 :
Graphs
නිවැරදි කිරීමක්:
පසුගිය සතිවල පළවූ 8 වන, 9 වන සහ 10 වන ලිපි
වල (BST සම්බේධ) මාතෘකාව නවනස් විය යුතුයි.
එය Non linear Data Structures – Part 1 නලස
නවනස් වියයුතුයි... Linear
Data Structures නකොටසට
අයත් වේනේ Linked List,
Stack සහ Queue වන අතර
Non linear Data Structures
නකොටසට අයත් වේනේ
Multidimensional
Arrays, Binary Sorted
Tree(BST) සහ Graphsය.
නම් වනචිට අපි Linear Data
Structures සයල්ලමත් Non
linear Data Structures වල
BST ගැනත් කතා කළා....
අද අපි අවධානය නයොමු
කරේනේ Graphs ගැනයි.
Graphs abstract data
type එකක්. Graph එකක්
නකොටස් නදකකිේ සමේවිතයි. එනම්, Edges (or
Arcs) සහ Vertices (or Nodes) එ නකොටස්
නදකයි. අපි ඒවාට ordered pairs යැයි කියමු.
ඉහත දැක්නවේනේ vertices 6ක් සහ edges 7ක්
ඇති labled graph එකක්...
Graphs වලින් කළ හැකි දේවල් ද ොනවද?
1. Nodes දදකක් අතර දකටි දුර දෙවී . ද ය
ඕදන ලක්ෂ/ේථාන දදකක් අතර දකටි දුර
දෙවී ට උදයෝගීකර ගතහැකිය.දේ ෙඳහා
උදාහරණ සුලභව දැකිය හැකිය. එනේ සිතිය ක
යේ ලක්ෂ දදකක් (ද ොදහෝවිට නගර දදකක්) අතර
දකටි දුර දෙවී , පරිපථ ෙටහනක යේ තැන්
දදකක් අතර අව දුර දෙවී වැනි දේවල්....
2. යේ ලක්ෂයකට අෙලින් ඇති ලක්ෂ
හඳුනාගැනී .
* මීට අමතරව අනනකුත් ATD වල කරන
traversal, insertion, deletion operations
නමහිදී ද කළ හැකිය.
දේ ගැන කරුණු දෙොයේදී ට අන්තර්ජාලදයන්
හමුවුනු ෙටහනක් පහතින් දපන්වන්නේ; එය
Graphs දකොතරේ සුලභව භාවිතා දකදරනවද
යන්න ඔ ට පෙක් කරාවි.
TYPES of GRAPHS:
Graphs වර්ග නබොනහොමයක් ඇතත් අපි ඉතා
බහුලව නයොදාගැනනන වර්ග කීපයක් ගැන
පමණක් කතා කරමු.
1. Directed Graphs
Directed Graph එකක් පහත පරිදි හැඳිේනේ.
A directed graph or digraph is an ordered pair
D = (V, A).
Directed graph එකක් හැඳිේවීමට එහි අඩංගු
Vertices සහ vertices යුගලක් එකට යා නකනරන
Arcs නයොදාගැනේ. එය මනාවට පහත
උදාහරණනයේ පැහැදිලි නේ.
A directed graph D=(V,A) consists of
1. A finite non-empty set of vertices V=V(D)
2. An arc set, A=A(G), where each arc in A is assigned
an ordered pair of vertices, a=(u,v).
If a=(u,v) then a joins u to v,
u is the origin, tail, initial vertex of a
v is the terminus,head, terminal vertex of a.
2. Undirected Graphs.
An undirected graph is one in which arcs have no
orientation. The arc (a, b) is identical to the arc
(b, a), i.e., they are not ordered pairs, but sets
{u, v} (or 2-multisets) of vertices.
An undirected graph:
To be continued next week!
13. Data Structures වරල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසිංශ විසිනි
Non linear Data Structures – Part 2:
Graphs (contd.)
පසුගිය වතිනේ අපි ප්රcධානමම Graphs ලර්ග (Directed and
Undirected) ගැම කතන කෂන....අදත් අපි තලදුරටත්,
බහුලල භනවිතන නලම Graphs ලර්ග ගැම කතන කරමු....
Weighted Graphs
සියලුම edges ලට අගයේ (values) බනදී තිනබම
graphs, weighted graphs නව ශඳුේලමලන. ඉශත
නපේලන ඇත්නත් weighted undirected graph එකක්.
ඉශත නපේලන ඇත්නත් weighted directed graph එකක්.
A practical example for a weighted directed graph
තලත් graph classification එකක් නව complete වශ
incomplete graph ශැඳිේවිය ශැකිය. (These
classifications are theory parts of graphs)
Examples for complete graphs:
An example for undirected graphs:
An example for directed graphs:
ඉශත ලර්ගීකරණයේ වමග ඒලනට වම්බේධා උදනශරණ
කීපයක් තමයි ඉශත දක්ලන ඇත්නත්
නමනතක් ඉනගම ගත් නේල නකටි වටශමක් :
Graph: A graph contains vertices and edges.
Directed graph: The edges of the directed graph
are pointing only in one direction.
Weighted graph: all edges are weighted
Complete graph: all vertices are connected to
each other.
Note: අපි graphs ගැම ඉනගම ගේම කලිේ tress ගැම
ඉනගම ගත්තන මතක ඇති......Trees කියේනමත් යම්
විනේ graph එකක්…
A tree is a directed graph. Each vertex as one parent
vertex, except the root vertex. The root vertex has no
parent...
තල අලුත් definitions නදකක්:
Cycle: Traversing the graph at least one vertex will be
visited more than once (loop).
Cycle test
Directed graphs might have cycles. Cycles are endless
loops while traversing the graph. On undirected
graphs each edge is a cycle.
Spanning tree: A tree is a sub graph containing a sub
set of all edges.
Weighted Graph එකක cheapest network එක එහි
minimum spanning tree එකයි.
Creating a minimum-cost spanning tree
Examples are taken from the internet
To be continued next week
14. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
Non linear Data Structures – Part 2 :
Graphs – Contd.
Graph representations
අද අපි අධ්යsනය කරේනේ graph representations
ගැනයයි. ක්රnම නදක් ියන නයව .... Graph එකක nodes
සහ edges ඇිය ආක ර ට අපි නේ representation එක
කරමු.
1. Adjacency matrix
අපි උද හරණ කිේම නම නේරුේ ගනිමු.
එකකිේ නපේනුේ කරේනේ ඒ ඒ node එකට edge
එකකිේ සේබේධ්ය nodes . ඒ සඳහ න ොද
ගැනනයේනේ 2-D array එක් . ඉහත graph එක සහ
matrix (2D array) එක බලේනය. Nodes නදක්
සේබේධ්ය නයේ 1 ද නයැේනයේ 0 ද න ොද ගැනේ.
Undirected graph එකකදී නම සරල අතර එකකදී නේ
දිශ ව අනුව එක නවනයස් නේ....
An adjacency matrix is a representation of vertices
(or nodes) of a graph, which are adjacent to which
other vertices. An adjacency matrix is a two
dimensional array in which the elements indicate
whether an edge is present between two vertices.
An edge between two vertices is indicated with a 1;
while the absence of a edge is indicated by a 0. An
example graph and its adjacency matrix is shown
above. For example in the above figure vertex ’2′ is
adjacent to vertices 1,3 and 5.
පහත උද හරණ නදක බලේනය:
The adjacency matrix for figure 1 (undirected graph):
a b c d e
a 0 1 0 0 0
b 1 0 1 1 0
c 0 1 0 1 1
d 0 1 1 0 1
e 0 0 1 1 0
The adjacency matrix for figure 2 (directed graph):
a b c d e
a 0 1 0 0 0
b 0 0 1 1 0
c 0 0 0 0 1
d 0 0 1 0 0
e 0 0 0 1 0
2. Adjacency lists
නම ද අපි උද හරණ කිේම නම නේරුේ ගනිමු.
ඉහත සටහනයට අනුව, a node එක tail එක නලසේ, b
node එක head එක නලසේ හඳුේවමු. Arc/Edge එක
ේනේ a සිට b ට… b head වී, a tail වුනු විට අපි, “ is
adjacent to node ” යි කි මු
දැේ අපි බලමු පහත graph එක adjacency list
ආක රන ේ represent කරේනේ නකනසේද කි .
Directed Graph:
Adjacency list representation
Moe examples to show more representations of
adjacency lists and matrices:
Adjacency list representation of an Undirected graph
(Example)
Adjacency list representation of a directed graph
(Example)
Adjacency matrix representation of an undirected graph
(Example)
Adjacency matrix representation of a directed graph
(Example)
Examples are illustrated from the internet sources!
To be continued in the next week!
15. Data Structures ඳරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
Nonlinear Data Structures – Part 2: Graphs
– Contd.
අද අපි අලධානය නයොමු කරේනේ undirected graph
operations, C++ Coding ලලිේ කරේනේ නකොනහොමද
කිය....
මුලිේම අපි ඳහත undirected graph එක සහ ඊට
අදාළ adjacency matrix එක ගනිමු. (This example is taken
from the internet)
Undirected Graph with 5 nodes and 5 edges:
Related adjacency matrix of the graph:
ඳසුගිය සතිනේ මම කිය දුේනු graph representations ඔබට
මතක නම්, නම් adjacency representation එක ඉතා සරල
ඔබට අලනබෝධ නේවි .නහොයි දැේ ඔබ බේන ඳහත C++
code එක:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
class Graph {
private:
bool** adjacencyMatrix;
public:
int vertexCount;
void intializeGraph(int vertexCount)
{
this->vertexCount =
vertexCount;
adjacencyMatrix = new
bool*[vertexCount];
for (int i = 1; i <=
vertexCount; i++) {
adjacencyMatrix[i] = new
bool[vertexCount];
for (int j = 1; j <=
vertexCount; j++)
adjacencyMatrix[i][j] = false;
}
}
void addEdge(int i, int j) {
if (i >= 1 && i <= vertexCount
&& j >= 1 && j <= vertexCount) {
adjacencyMatrix[i][j] =
true;
adjacencyMatrix[j][i] =
true;
}
}
void removeEdge(int i, int j) {
if (i >= 1 && i <= vertexCount
&& j >= 1 && j <= vertexCount) {
adjacencyMatrix[i][j] =
false;
adjacencyMatrix[j][i] =
false;
}
}
bool isEdge(int i, int j) {
if (i >= 1 && i <= vertexCount
&& j >= 1 && j <= vertexCount)
return
adjacencyMatrix[i][j];
else
return false;
}
void printMatrix()
{
for (int i=1; i<=vertexCount;
i++)
{
for (int j=1; j<=vertexCount;
j++)
{
if (isEdge(i,j))
{
printf("Matrix[%d][%d]",i,j);
printf("n");
}
}
}
}
}myGraph;
int main()
{
printf("nUndirected Graph
Operationsn");
printf("---------------------------
n");
//Initialize the graph (It has 5
nodes)
myGraph.intializeGraph(5);
printf("No.of Nodes: %d n",
myGraph.vertexCount);
//Now add vertices
myGraph.addEdge(1,4);
myGraph.addEdge(4,2);
myGraph.addEdge(4,5);
myGraph.addEdge(2,5);
myGraph.addEdge(3,5);
//Print the relevant edges
printf("nEdges in your graph (denoted
by each matrix element):nn");
myGraph.printMatrix();
getch();
return 0;
}
Output:
16. Data Structures පරිගණක ඉංජිනේරු, තරිඳු වීරසිංශ විසිනි
Nonlinear Data Structures – Part 2: Graphs
– Contd.
අද අපි බේනේ Directed Graph එකක් නකොනශොමද
C++ ලලිේ implement කරේනේ කියා....ඔබ, කලිේ
adjacency matrix එක වශ C++ ලැඩවටශන නශොඳිේ
අධ්යනය කෂා න් නමය අලනබධධ් කරගැීමම ඉතා
පශසුයි!
අනේ Directed Graph එක පශත අයුරිේ තිනේ යයි
සිතමු!
අදාෂ adjacency matrix එක:
මතක තබාගේන, නමහිදී arrow head එනක් දිාලට
ඇති node එක පමණක් '1' ේ දැක්නේ.....
උදාශරණයක් නව 1 සිට 4 ට edge එකක් තිනබනලා.
නමහිදී එනක් 1,4 element එක '1' නව දැක්නලන අතර
4,1 element එක '0' නේ...
න් නලනව ඔබ නේරු් ගේන ගිය වතිනේ මේරි් එකේ
වමග ගපානගන!
C++ Implementation (pretty similar to the last one
expect the small changes in the adjecency matrix):
Please note that I have used Visual C++ to write &
run the following code (no difference in the C++
coding syntax)
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
class Graph {
private:
bool** adjacencyMatrix;
public:
int vertexCount;
void intializeGraph(int vertexCount) {
this->vertexCount = vertexCount;
adjacencyMatrix = new
bool*[vertexCount];
for (int i = 1; i <= vertexCount;
i++) {
adjacencyMatrix[i] = new
bool[vertexCount];
for (int j = 1; j <=
vertexCount; j++)
adjacencyMatrix[i][j]
= false;
}
}
void addEdge(int i, int j) {
if (i >= 1 && i <= vertexCount &&
j >= 1 && j <= vertexCount) {
adjacencyMatrix[i][j] =
true;
//This is the
logic change w.r.t last week program
/*adjacencyMatrix[j][i] =
true;*/
}
}
void removeEdge(int i, int j) {
if (i >= 1 && i <= vertexCount &&
j >= 1 && j <= vertexCount) {
adjacencyMatrix[i][j] =
false;
adjacencyMatrix[j][i] =
false;
}
}
bool isDirectedEdge(int i, int j) {
if (i >= 1 && i <= vertexCount &&
j >= 1 && j <= vertexCount)
return
adjacencyMatrix[i][j];
else
return false;
}
void printMatrix()
{
for (int i=1; i<=vertexCount; i++)
{
for (int j=1; j<=vertexCount;
j++)
{
if (isDirectedEdge(i,j))
{
printf("Matrix[%d][%d]",i,j);
printf("n");
}
}
}
}
~Graph() {
for (int i = 0; i < vertexCount;
i++)
delete[] adjacencyMatrix[i];
delete[] adjacencyMatrix;
}
}myGraph;
int main()
{
printf("nDirected Graph Operationsn");
printf("---------------------------
n");
//Initialize the graph (It has 5 nodes)
myGraph.intializeGraph(5);
printf("No.of Nodes: %d n",
myGraph.vertexCount);
//Now add vertices
myGraph.addEdge(1,4);
myGraph.addEdge(4,2);
myGraph.addEdge(4,5);
myGraph.addEdge(5,2);
myGraph.addEdge(3,5);
//Print the relevant edges
printf("nDirected Edges in your graph
(denoted by the relevant matrix
element):nn");
myGraph.printMatrix();
getch();
return 0;
}
Output in the console:
Wish you all a Happy New Year 2013! Collect these
articles and learn to be a good programmer!
17. Data Structures සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Nonlinear Data Structures – Part 3: M-
arrays
අපි අද මුලිේම නේ ලිපි නපනෙහි අතීතය ගැන මතක
අවර්ජනයක් කරමු. දැේ, ඔබ අද නේ ලිපිය ඉදිරියට
කියවේනට කලිේ, මම කැමතියි ඔබ ෙඟ ඇති 2012
ජූලි 4 වනදා විදුසර පත්තනර් ආපහු අරගේනවනේ.
(පරණ පාඩේ ඔබ එකතු කරේ ඉේනවා කියල තමයි මම
හිතේ ඉේනේ... ) එදා තමයි අපි Data Structures
& Algorithms ලිපි නපෙ පටේ ගත්නත්. ඒ ලිපිනයහි
මම කියා තිනබනවා නකොනහොමද ඉදිරියට ලිපි නපෙ
සකස්නවේනේ කියල.....ඔබට නපනනනවා ඇති,
මුලිේම අපි Data Structures ගැන කතා කරලා පසුව
Algorithms පැත්තට එන බව සඳහේ කරලා තිනබන
විත්තිය. ඒවනේම, Data Structures පහත ආකාරයට
නකොටස් නදකකට නබදා ඒ නකොටස් වල අංගයේ නවන
නවනම ඉදිරිපත් කරන බව.
1. Linear Data Structures:
a. Ordered List b. Stack c. Queue
2. Nonlinear Data Structures:
a. Multidimensional arrays b. Trees c. Graphs
ඉතින් ඒ අනුව ඔබ දන්නවා මේ වන විට අපි සරලව Data
Structures වල මූලික සිද්ධාන්ත සහ ඒවාමේ C++/C#
implementations මෙන ආ බව. (Linked Lists, Stacks,
Queues වමේම BSTs, Graphs ෙැනත් අපි කතා කළා...)
ඒ අනුව අපට Data Structures වලින් ඉතුරුව ඇත්මත්
Multidimensional Arrays පමණයි.
වැදගත්: Nonlinear Data Structures වලට අදාළ
Multidimensional Arrays ෙැන මම මුලින් සාකච්ඡා
කමළේ නැත්මත් ඒ ෙැන ඔබ දැනටමත් (මේ පාඩේ
මාලාවට කලිනුත්) දන්නා නිසාමවනි. මේ ෙැන සරල
හැඳින්වීමක් , මා ඉදිරිපත් කළ ‘C programming
language’ ලිපි මපමළහි එක් ලිපියක මෙන ආවා. (2010
අමේේල 21) මකමසේ මවතත් Multidimensional Arrays
ෙැන සරලව අද මේ ලිපිමයන් කතා කර, ඉන්පසුව අපි
Algorithms ෙැන අවධානය යමු කරමු.
තවත් වැදෙත් මදයක්: මම මේ පාඩේ මාලාව මෙන
එන්මන් Data Structures & Algorithms ෙැන මූලික
වමේම මත්මරන අයුරින් නිසි අවමබෝධයක් ලබා
මදන්නයි. ඒ දැනුම වර්ධනය කරෙැනීම සහ වැඩි දියුණු
කරෙැනීම ඔබමේ වෙකීමක්. (අන්තර්ජාලමයන්, මේ
ෙැන ඇති මපොත් මගින්) ඔබ පරිෙණක ක්ම ේත්රණයන්හි,
මෘදුකාාංෙ ක්ම ේත්රණයන්හි නිරත වීමට බලාමපොමරොත්තුව
ඉන්නවා නේ එය අනිවාර්ය මදයක්!
Multidimensional Arrays:
Multidimensional Arrays කියන්මන් Arrays of Arrays
මලස හඳුන්වන්න පුළුවන්. මමය සරලව පහත සටහමනන්
දක්වන්න පුළුවන්:
අපි උදාහරණයකිේ නේ ගැන වැඩි දුර ඉනගන ගනිමු:
3X3 Matrix Multiplication:
1 2 3
4 5 6
7 8 9
C# Coding:
using System;
namespace MetrixMultiplcation
{
class Program
{
static void Main(string[] args)
{
/*Two 3-D arrays (p & q)*/
int[,] p = new int[3,3]{
{1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[,] q = new int[3,3]{
{2, 1, 2}, {2, 1, 2}, {2, 1, 2} };
/*This is the resultant
matirx - now all elements are set to
0*/
int[,] r = new int[3,3]{
{0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
multiplyMatrices(p, q, r);
printMultipliedMatrix(r);
Console.ReadKey();
}
//Method to Multiply
static void multiplyMatrices(int[,] a,
int[,] b, int[,] result)
{
int i, j, k;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
for(k = 0; k < 3;
k++)
{
result[i,j] +=
a[i,k] * b[k,j];
}
}
}
}
//Method to Print
static void printMultipliedMatrix(int
[,]x)
{
int i, j;
for (i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
Console.WriteLine(x[i,j] + " ");
}
Console.WriteLine("n");
}
}
}
}
In C:
#include <stdio.h>
void mult_matrices(int a[][3], int
b[][3], int result[][3]);
void print_matrix(int a[][3]);
int main()
{
int p[3][3] = {{1, 2, 3},{4, 5,
6}, {7, 8, 9}};
int q[3][3] = {{2, 1, 2}, {2, 1,
2}, {2, 1, 2}};
int r[3][3] = {{0, 0, 0}, {0, 0,
0}, {0, 0, 0}};
multiplyMatrices(p, q, r);
printMultipliedMatrix (r);
}
void multiplyMatrices (int a[][3],
int b[][3], int result[][3])
{
int i, j, k;
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
for(k = 0; k <
3; k++)
{
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
void printMultipliedMatrix (int
a[][3])
{
int i, j;
for (i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%dt",
a[i][j]);
}
printf("n");
}
}
Next Week Onwards: Algorithms
2 1 2
2 1 2
2 1 2
18. පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
අද සට ලිපි කිහිපයකිේ අපි අවධානය නයොමු
කරේනේ, Data Structures වලට අදාළ,
බහුලව ඉගැේනවන සහ භාවිතානවන
Algorithms කිහිපයක්.
මෙෙ ලිපි මෙමෙහි ම ොමෙොස්වන (Part 12)
ලිපිමෙන් (Graphs වලට අ ාෙ) ෙෙ Spanning
Trees ගැන සරල හැඳින්වීෙක් කො. (ෙතකෙ
ආවර්ජනෙ කරන්න) ඉතින් අ ෙෙ කිොම න්මන්
Graph එකක (Wieghted Graph) Minimum
Spanning Tree එක මහොෙන algorithms ගැනයි.
Spanning Tree:
A tree is a sub graph containing a sub set of
all edges.
Minimum Spanning Tree:
Spanning tree of minimum total weight
Weighted Graph එකක cheapest network
එක එහි minimum spanning tree එකයි.
Minimum Spanning Tree සංකල්ෙෙ භාවිතාවන
ප්රාාමෙිකක උ ාහරණෙක්:
මගොඩනැකල්ලක ෙරිඝණක සිෙල්ල, අඩුෙ cable
ප්රාොණමෙන් ස්බනන් කරන්නටන්බ මකමසේ
ස්බනන් කෙ යුතු ? මෙහිදී Minimum Spanning
Tree සංකල්ෙෙ මෙො ාගත හැකිෙ.
Minimum Spanning Tree මසොෙන්නට ප්රා ාන
algorithms ම කක් තිමනනවා.
1. Prim-Jarnik Algorithm
2. Kruskal Algorithm
Prim-Jarnik Algorithm
Grows the tree T one vertex at a time
Cloud covering the portion of T already
computed
Labels D[v] associated with vertex v
If v is not in the cloud, then D[v] is the
minimum
weight of an edge connecting v to the
tree
After calculating the minimum spanning tree:
Algorithm in a nut-shell:
1. කුෙක් මහි Vertex එකක් මතිරාගන්න.
2. එයින් විහිම න සිෙලුෙ අතු (edges)
සලකන්න. අඩුෙ අගෙ ඇති අත්ත (least
weighted edge) එක, එමහෙ නැත්න්බ
අමනක් විදිහට කිව්මවොත්, ෙඟින්ෙ ඇති
Vertex මතිරාගන්න.
3. ැන් ඔනට Vertices ම කක් තිමනනවා.
ැන්, ඒ Vertices ම මකන් කුෙන මහි
එකකට ෙඟින්ෙ ඇති මවනත් Vertex එකක්
මතිරාගන්න. ම්බ විදිහට දිගටෙ කරන්න.
(ඊෙඟට ඔනට තිමනන්මන් Vertices 3 කින්
කුෙක් මහි එකකට ෙඟ මවනත් Vertex
එකක් මතිරා ගන්නයි.)
4. මෙමලස මතිරමින් ෙනවිට, ඔනට
මතිරාගැනීෙට ඇති Edge එක(අඩුෙ අගෙ
ඇති) මහි ෙඟින්ෙ ඇති Vertex එක ඔන
ැනටෙත් මතිරාමගන න්බ, ඔන ඔමේ
Minimum Spanning Tree එක මතිරාමගන
අවසන්...
Pseudo code:
1 for each vertex u in graph G
2 set key of u to _
3 set parent of u to nil
4 set key of source vertex to zero
5 enqueue to minimum-heap Q all vertices
in graph G.
6 while Q is not empty
7 extract vertex u from Q // u is the vertex
with the lowest key
that is in Q
8 for each adjacent vertex v of u do
9 if (v is still in Q) and (weight-
function(u, v) < key of v) then
10 set u to be parent of v //
in minimum-spanning-tree
11 update v's key to equal
weight-function(u, v)
තවත්, රූපමය උදාහරණයක්:
මුල් Graph එක සහ ලනාගත් Minimum Spanning Tree
එක:
නේ රූප නදක සමඟ ඉහත දැක්වූ විස්තරය
සංසේදනාත්මකව කියවේන..
ැන්, ඔනට කැෙති ඕමනෙ ෙරිඝනක භාෂාවකින් මෙෙ
ඇල්මගොරිතෙ implement කෙ හැකිෙ.
අපි ලබන සතිනේ ඒ ගැන කතා කරමු.
References:
http://www.cs.purdue.edu/homes/ayg/CS251/slides/chap10b.pdf
http://ku.edu.np/cse/faculty/manoj/daa/prim.pdf
http://www.brpreiss.com/books/opus4/html/page577.html
Algorithms related to Data Structures
19. පරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
(Continuing from last week)
Prims- Jarnik Algorithm in C++
උපරිම Vertices ගණන 20 ක් වන පරිදි පහත
program එක සැකසී ඇත...This is a simple
implementation of Prim’s algorithm in-order to
understand the algorithm easily!
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
int
weight[20][20],visited[20],d[20]
,p[20];
int v,e;
void creategraph()
{
int i,j,a,b,w;
cout<<"nEnter number of
vertices: ";
cin>>v;
cout<<"nEnter number of
edges: ";
cin>>e;
/*Initializing the Graph*/
for(i=1;i<=v;i++)
for(j=1;j<=v;j++)
weight[i][j]=0;
for(i=1;i<=v;i++)
{
p[i]=visited[i]=0;
d[i]=32767; /*Max int
value*/
}
for(i=1;i<=e;i++)
{
cout<<"nEnter edge a,b and
weight w:";
cin>>a>>b>>w;
weight[a][b]=weight[b][a]=w;
}
}
void prim()
{
int
current=1,totalvisited=1,mincost,
i;
d[current]=0;
visited[current]=1;
while(totalvisited!=v)
{
for(i=1;i<=v;i++)
{
if(weight[current][i]!=0)
if(visited[i]==0)
if(d[i]>weight[current]
[i])
{
d[i]=weight[current][i];
p[i]=current;
}
}
mincost=32767;
for(i=1;i<=v;i++)
{
if(visited[i]==0)
if(d[i]<mincost)
{
mincost=d[i];
current=i;
}
}
visited[current]=1;
totalvisited++;
}
mincost=0;
for(i=1;i<=v;i++)
mincost+=d[i];
cout<<"nMinimum
cost="<<mincost<<"n";
cout<<"nMinimum spaning tree
is: ";
for(i=1;i<=v;i++)
cout<<"nVertex "<<i<<" is
connected to "<<p[i] <<".";
}
int main()
{
creategraph();
prim();
getch();
return 0;
}
Reference: http://ankitstar.blogspot.com/2011/05/prims-algorithm.html
Algorithms related to Data Structures
20. පරිගණක ඉංජිනේරු, තරිඳු වීරසිංහ විසිනි
ඔබට මතක ඇති, පසුගිය සති නදනේදී අපි කතා කනළේ,
Weighted Graph එකක Minimum Spanning Tree එක
නසවීමට නයොදාගේන ප්රධානතම Algorithm නදනකේ
එකේ ලන Prim’s – Jarnik’s Algorithm එක
ගැනයි....දැේ අද අපි කතා කරේනේ, අනනේ
Algorithm එක, ඒ කියේනේ, Kruskal’s Algorithm
එක ගැනයි.....
Kruskal’s Algorithm:
සරලම කිව්නලොත්, නමයිේ කියනලේනේ: “සියලුම
edges මුලිේම weight එක ලැඩිලන පිළිනලට අධයනය
කර, අඩුම weight එක ඇති edge එක minimum
spanning tree එක හදන කුකයට (set) ඇතුළත්
කරේන...”
නමය ඉතාම සර අර්ථයයි...නමුත් ඉහත කී “minimum
spanning tree එක හදන කුකයට (set) ඇතුළත්
කරේන...” යේනනහි තල ඉනගන ගතයුතු නේලල්
තිනබනලා....
Scan all edges in increasing weight order; if an edge
is safe, keep it (i.e. Add it to the set A). [1]
අපි දැේ බමු, නේ algorithm එක නකොනහොමද
ක්රියාත්මක නලේනේ කිය.....(In detail)
Algorithm in a nutshell [2]:
G = Graph
V = Set of Vertices
E = Set of Edges
Let G = (V, E) be the given graph,
with |V| = n
{
Start with a graph T = (V, Φ)
consisting of only the vertices of
G and no edges;
/* this can be viewed as n
connected components, each vertex
being one connected component */
Arrange E in the order of
increasing costs;
for (i = 1, i$ leq$n - 1, i
+ +)
{
Select the next smallest
cost edge;
if (the edge connects
two different connected components)
add the edge to T;
}
}
නමය අලසානනේ අපට Minimum Spanning Tree එක
ඉතුරු නලයි…..
අපි දැේ පියලනරේ පියලර නගොඩ නැනගන
උදාහරණයේ බමු: [2]
Sample Graph and steps to get its MST:
නමලේ උදාහරණ කීපයේ අධයනය කර ඔබට නමම
algorithm එක නත්රුේ ගත හැකි නව්වි...අපි බන
සතිනේ නමහි C++ coding එක බමු:
Reference:
[1]http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithm
s/GraphAlgor/kruskalAlgor.htm
[2] http://lcm.csa.iisc.ernet.in/dsa/node184.html
Algorithms related to Data Structures
21. පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
නේ සතිනේ අපි අවධානය නයොමු කරේනේ මා
පසුගිය සතිනේ කියලා දුේ Kruskal’s Algorithm
එනකහි C++ implementation එකයි...
නමහි මුලිේම ඔනේ Graph එනේ Nodes සංඛ්යාව
සහ Edges සංඛ්යාව ලබාදී අනතුරුව අදාළ nodes
(u,v) සහ ඒ nodes නදක යා කරන edge එනේ
weight (w) එක පිළිනවලිේ ලබානදේන. ඒ අනුව
නේ program එක අදාළ Graph එක මුලිේම
හදාගනී...පසුව Kruskal’s Algorithm එක run
කර අදාළ Minimum Spanning Tree (MST)
එක ලබා නදයි. නමය ඔබ නිදහනසේ අධයනය කළ
යුතුයි.....
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define edge pair< int, int >
#define MAX 1001
// ( w (u, v) ) format
vector< pair< int, edge > > GRAPH,
MST;
int parent[MAX], total, N, E;
int findset(int x, int *parent)
{
if(x != parent[x])
parent[x] =
findset(parent[x], parent);
return parent[x];
}
void kruskal()
{
int i, pu, pv;
sort(GRAPH.begin(),
GRAPH.end()); // increasing weight
for(i=total=0; i<E; i++)
{
pu =
findset(GRAPH[i].second.first,
parent);
pv =
findset(GRAPH[i].second.second,
parent);
if(pu != pv)
{
MST.push_back(GRAPH[i]);
// add to tree
total += GRAPH[i].first;
// add edge cost
parent[pu] = parent[pv];
// link
}
}
}
void reset()
{
// reset appropriate variables
here
// like MST.clear(),
GRAPH.clear(); etc etc.
for(int i=1; i<=N; i++)
parent[i] = i;
}
void print()
{
int i, sz;
// this is just style...
sz = MST.size();
for(i=0; i<sz; i++)
{
printf("( %d",
MST[i].second.first);
printf(", %d )",
MST[i].second.second);
printf(": %dn",
MST[i].first);
}
printf("Minimum Cost: %dn",
total);
}
int main() //This is the execution
part
{
int i, u, v, w;
printf("nEnter No. of Nodes and
Edges (Differ with a space): ");
scanf("%d %d", &N, &E);
reset();
for(i=0; i<E; i++)
{
printf("nEnter the relevant
weight and two nodes - u, v = nodes
and w = wieght: ");
scanf("%d %d %d", &u, &v,
&w);
GRAPH.push_back(pair< int,
edge >(w, edge(u, v)));
}
kruskal(); // Run Kruskal and
construct the MST vector
print(); // Print the MST edges
and weights
return 0;}
Reference: http://zobayer.blogspot.com/2010/01/kruskals-
algorithm-in-c.html
Algorithms related to Data Structures
22. Algorithms related to Data Structures
නේ සතිනේ අපි අවධානය නයොමු කරේනේ Graph
Theory ලට අදාළ Searching Algorithms
දදකක් ලන Breadth First Search ලන Deapth
First Search ගැනයි. මුලින් අපි ඒ Algorithms
දදක ගැන කතා කර පසුල ඒලාදේ
Implementation ගැන කතා කරමු.
Breadth First Search (BFS):
මෙය, Root එමෙන් පටන් මෙන අසල්ලාසී nodes
(Neighbouring nodes) මසොයා යයි. ඉන්පසු ඒ
nodes ලට සම්බන්ධ, ෙලින් මසොයා මනොගිය
nodes මසොයයි....
ඉහත Binary Tree එදක් BFS එක ලියා
දැක්වුදලොත්:
Starts with the root, a then go to its
children (b & c), then go to b’s children (d
& e), then c’s children (f & g) and finally e’s
child (h).
තලත් උදාහරණයක්:
හිතන්න ඔබට දහොයන්න ඕදන් Node 3 කියා…
BFS එක යන්දන් දේ අනුපිලිදලටයි:
5->2->8->0->1->3 (found!)
BFS Algorithm:
The BFS algorithm uses the ‘queue’ data
structure (that we learnt during our data
structures lessons) to store intermediate results as
it traverses the graph, as follows:
1. Enqueue the root node
2. Dequeue a node and examine it
o If the required element is found in
this node, quit the search and return
a result.
o Otherwise enqueue any successors
(the direct child nodes) that have not
yet been discovered.
3. If the queue is empty, every node on the
graph has been examined – quit the search
and return "not found".
4. If the queue is not empty, repeat from Step
2. [1]
Deapth First Search (DFS):
Root එමෙන් පටන් මෙන sub tree එෙෙ මෙළලරටෙ
(අන්තිෙ node එෙ දක්ලාෙ) යයි…
Above two slides were taken from [2].
Consider the above graph:
After Depath First Search we do have the following
tree:
Note: In implementation DFS uses stacs instead of
queues
Next Week: BFS and DFS in coding
Reference:
[1] http://en.wikipedia.org/wiki/Breadth-first_search
[2] www.cs.ust.hk/~huamin/COMP171/dfs.ppt
පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
23. Algorithms related to Data Structures
වැදගත්: නෙෙ ලිපිය පසුගිය සතිනේ ලිපියට කලිේ
පළවිය යුතු වුවත් මුද්රණ නදෝෂයක් නිසානවේ පසු
ගිය සතිනේ, පළ වනේ නේ සතිනේ පළවිය යුතුව
ලිපියයි. එබැවිේ ඔබ ඔබනේ ලිපි එකතුව ඒ අනුව
සකසා ගේන...
නේ සතිනේ අපි අවධානය නයොමු කරේනේ Breadth
First Search හි (BFS) C++ Implementation එක
ගැනයි..
මතක තබාගන්න, මේ ලිපි මෙළ හරහා ඉදිරිෙත්
කළ මමලැනි ලැඩසටහන්, ඔබ තනිලම ලියා පුරුදු
ලන්න...මමම උදාහරණ බමින් තනිලම ඉමගන
ගන්න.... නැලත නැලත බන්න...එවිට ඔබට මේ කරුණු
ලැඩිලැඩිමයන් මත්රුේ යාවි .....
Note: In this implementation, queue data structure is
used to store the paths. It is the usual way of
implementing BFS.
#include <iostream>
#include <queue>
using namespace std;
const int maxx = 20;
void Read_input_from_user(bool
grid[][maxx], int vertices)
{
int u, v;
for(int x = 0; x < vertices; ++x)
{
cout << "nEnter u : t";
cin >> u;
u--;
cout << "nEnter v : t";
cin >> v;
v--;
grid[u][v] = true;
grid[v][u] = true;
cout << "---------------------
n";
}
}
void BFS(queue<int> &Q, vector<int>
&trace, bool grid[][maxx], int start,
int nodes)
{
int u;
vector<int> visited(maxx,0);
Q.push(start);
trace[start] = -1;
visited[start] = 1;
do{
u = Q.front();
Q.pop();
for(int v = 0; v < nodes; ++v)
{
if((grid[u][v] == true) &&
visited[v] == 0)
{
Q.push(v);
trace[v] = u;
visited[v] = 1;
}
}
}while(!Q.empty());
}
void Trace_result(vector<int> &trace,
int start, int end, int nodes)
{
cout << "From node" << start + 1 <<
" you can visit :n";
for(int v = 0; v < nodes; ++v)
{
if(trace[v] != 0)
{
cout << "node : " << v + 1
<< " , ";
}
}
cout << "n------------------------
---n";
if(trace[end] == 0){
cout << "Unavailable.! to go to
from " << end + 1
<< " to -> " << start + 1
<< 'n';
}
else{
while(end != start)
{
cout << end + 1 << "<-";
end = trace[end];
}
cout << start + 1 << endl;
}
}
int main()
{
//Initialization
vector<int> trace(maxx, 0);
queue<int> Q;
bool grid[maxx][maxx] = {false};
int nodes, vertices;
cout << "Input the number of Nodes :
n";
cin >> nodes;
cout << "Input the number of
Vertices : n";
cin >> vertices;
//Set value for all vertices.
Read_input_from_user(grid,
vertices);
//Read the necessary path
int starting_position,
finishing_position;
cout << "nInput the Starting Node :
n";
cin >> starting_position;
cout << "nInput the Finishing Node
: n";
cin >> finishing_position;
//Decrease to fit with index of C++
start from 0->size-1
starting_position--;
finishing_position--;
//Algorithm starts
BFS(Q, trace, grid,
starting_position, nodes);
Trace_result(trace,
starting_position, finishing_position,
nodes);
system("pause");
return 0;
}
Reference:
http://cboard.cprogramming.com/csharp-programming/150370-
breadth-first-search-csharp.html
පරිගණක ඉංජිනේරු ,තරිඳු වීරසංහ විසනි
24. Algorithms related to Data Structures
අද, නේ ලිපි මාානේ අලවේ ලිපියයි....පුරා ලිපි
24ක ඳරාවයක් තුෂ Data Structures වශ
Algorithms ගැන වර නමුත් නශො
අලන ෝධයක් ඔ ට ැන ේනට ඇතැයි
සතනලා...නේ ලිපි මාානේ අරමුණ වුනේ,
Computer Engineering නශෝ
Information Technology ක්නේව්ත්ර ල
නියැනේනට ානඳොනරොත්තු ලන, වරවවි
ලරේ ා ඇති වශ නලනත් ඳාඨමාාලේ
ශදාරන අයට නත්රුේ ගතශැකි ලන ඳරිදි Data
Structures වශ Algorithms ගැන නශො
දැනුේ අත්තිලාරමක් දමා දීමයි. අනේ කානේ
නමලැනි උදේ අඳට ැබුනේ නැතිමුත් අපි
තනිලම නේ නේලල් ඉනගන ගේනට උත්සුක
වුණා......දැේ දැේ ඔ ට ඇති අලව්ථා
න ොනශෝයි...ඒලායිේ ප්රනයෝනන
ගේන....අේතරනාය අලය නේට නිලැරදිල
ඳාවිච්ච් කරේන....ඳත-නඳොත ඳරිශීනය
කරේන...මූධර්ම නත්රුේ නගන කැමති
language එකකිේ (C++, Java, C#,
anyother) programming කරේන.
ඉතිේ දැේ අපි මු නේ ලිපි නඳෂ ශරශා උගත්
නේලල් වංශික්ඳතයක් නව:
Data Structures:
1. Linear Data Structures
a. Ordered List
b. Stack
c. Queue
2. Non Linear Data Structures
a. Multidimensional arrays
b. Trees
c. Graphs
Algorithms:
1. Searching Algorithms:
a. Breadth First
b. Deapth First
2. Shortest-Path Algorithms:
a. Kruskal’s
b. Prim’s
When it comes to algorithms. there are many
more for various purposes, for sorting data,
searching data, basically for all data operations
we have many algorithms but we learnt only 4
here. You must do some self learning
programming in-order to get a good knowledge
on all these types!
These are the data structures that we learnt:
List (Abstract View):
Stack (Abstract View):
Queue (Abstract View):
Mulitidimensional Arrays (Abstract View):
Trees (Abstract View):
Graphs (Abstract View):
නැලත නමලේ ලිපි නඳෂකිේ මුණ ගැනවමු!
ඔ උගත් නේ යළි යළිත් ප්රගුණණ කරේන.....
ඔ වැමට වාමය වතුට පිරි සුභ නල ලවරක් නේලා!
ඳරිගණක ඉංජිනේරු ,තරිඳු වීරසංශ විසනි