0% found this document useful (0 votes)
117 views36 pages

ASP Skripta

The document describes various data structures and algorithms including sequential searching, binary searching, stacks, queues, and linked lists implemented as LIFO and FIFO structures. Code examples in C++ are provided to demonstrate how to create classes for arrays, linked lists, stacks, queues and search algorithms. Main functions test the different data structures by adding elements, removing elements, and printing out contents.

Uploaded by

Nermin Boja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views36 pages

ASP Skripta

The document describes various data structures and algorithms including sequential searching, binary searching, stacks, queues, and linked lists implemented as LIFO and FIFO structures. Code examples in C++ are provided to demonstrate how to create classes for arrays, linked lists, stacks, queues and search algorithms. Main functions test the different data structures by adding elements, removing elements, and printing out contents.

Uploaded by

Nermin Boja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 36

SEKVENCIJALNO PRETRAZIVANJE

Seq.h
#include <iostream>
using namespace std;
template <class Type>
class nizlista
{
protected:
Type *Element;
int ArraySize;
public:
nizlista(int arraysize = 10) : ArraySize(arraysize),Element(new Type[arraysize]) {}
virtual ~nizlista();
friend ostream& operator<<<>(ostream& OutStream, const nizlista<Type>& OutList);
friend istream& operator>><>(istream& InStream,nizlista<Type>& InList);
};
template <class Type>
nizlista<Type>::~nizlista()
{
delete [] Element;
}
template <class Type>
ostream& operator<<(ostream& OutStream, const nizlista<Type>& OutList)
{
OutStream << "Uneseni elementi niza su:\n";
for (int element=0; element < OutList.ArraySize;element++)
OutStream << OutList.Element[element] << ' ';
OutStream<< endl;
OutStream << "Velicina niza je: " << OutList.ArraySize<< endl;
return OutStream;
}
template <class Type>
istream& operator>>(istream& InStream, nizlista<Type>& InList)
{
cout << "Unesite element niza:\n";
for (int element=0; element < InList.ArraySize;element++)
{
cout << "Element " << element << ": ";
InStream >> InList.Element[element];
}
return InStream;
}
template <class Type>
class pretlist : public nizlista<Type>
{
public:
pretlist(int arraysize = 10) :
nizlista<Type>(arraysize) {}
virtual ~pretlist() {}
virtual int trazi(const Type& Cilj) const;
};
template <class Type>
int pretlist<Type>::trazi(const Type& Cilj) const
{
for (int element=0; element < ArraySize; element++)
{
if (Element[element] == Cilj)
return element;
}
return -1;
}
Seqpret.cpp
#include "seq.h"
const int SIZE = 8;
int main()
{
pretlist<float> Lista(SIZE);
float Cilj;
int Pozicija;
cin >> Lista;
cout << Lista;
for (int i = 0; i < 4; i++)
{
cout << "Koji broj trazimo: ";
cin >> Cilj;
if ((Pozicija = Lista.trazi(Cilj)) != -1)
cout << "Broj je pronadjen na poziciji " <<Pozicija << endl;
else
cout << "Broj nije pronadjen u listi.\n";
}
return 0;
}

BINARNO PRETRAZIVANJE
Datalist.h
#include <iostream>
template <class Type>
class datalist
{
protected:
Type *Element;
int ArraySize;
public:
datalist(int arraysize = 10) : ArraySize(arraysize),
Element(new Type[arraysize]) {}
virtual ~datalist();
friend ostream& operator<<<>(ostream& OutStream, const datalist<Type>& OutList);
friend istream& operator>><>(istream& InStream, datalist<Type>& InList);
};
Datatemp.h
#include "datalist.h"
template <class Type>
datalist<Type>::~datalist()
{
delete [] Element;
}
template <class Type>
ostream& operator<<(ostream& OutStream, const datalist<Type>& OutList)
{
OutStream << "Elementi niza su:\n";
for (int element=0; element < OutList.ArraySize; element++)
OutStream << OutList.Element[element] << ' ';
OutStream << endl;
OutStream << "Velicina niza: " << OutList.ArraySize<< endl;
return OutStream;
}
template <class Type>
istream& operator>>(istream& InStream, datalist<Type>& InList)
{
cout << "Unesite elemente niza:\n";
for (int element=0; element < InList.ArraySize; element++)
{
cout << "Element " << element << ": ";
InStream >> InList.Element[element];
}
return InStream;
}
Binary.h
#include "datalist.h"
template <class Type>
class forgetsearch : public datalist<Type>
{
public:
forgetsearch(int arraysize=10) : datalist<Type>(arraysize) {}
virtual ~forgetsearch() {}
virtual int Search(const Type& Target) const;
};
Binarytemp.h
#include "binary.h"
#include "datatemp.h"
template <class Type>
int forgetsearch<Type>::Search(const Type& Target) const
{
int top=ArraySize-1, bottom=0, middle;
while(top > bottom)
{
middle = (top+bottom)/2;
if (Element[middle] < Target)
bottom = middle+1;
else
top = middle;
}
if (top == -1)
return -1;
if (Element[top] == Target)
return top;
else
return -1;
}

Binsearch.cpp
#include "bintemp.h"
const int SIZE = 10;
int main()
{
forgetsearch<int> List1(SIZE);
float Target;
int Location;
cin >> List1;
cout << List1;
for (int i = 0; i < 3; i++)
{
cout << "Unesite cijeli broj kojeg trazimo:";
cin >> Target;
if ((Location = List1.Search(Target)) != -1)
cout << "Broj je pronadjen na poziciji " << Location << endl;
else
cout << "Broj nije pronadjen.\n";
}
return 0;
}
STEK
Znakstack.h
#include <iostream>
using namespace std;
class znakstack
{
protected:
int StackSize;
char *Element;
int StackPointer;
public:
bool JeLiPrazan() const;
bool JeLiPun() const;
znakstack(int stacksize = 10);
virtual ~znakstack();
virtual bool Uzmi(char& TopElem);
virtual bool Ubaci(const char& NoviElem);
};
Znakstack.cpp
#include "znakstack.h"
znakstack::znakstack(int stacksize) : StackSize(stacksize), Element(new char[stacksize]), StackPointer(-1) {}
znakstack::~znakstack()
{
delete [] Element;
}
bool znakstack::JeLiPrazan() const
{
return StackPointer == -1 ? true : false;
}
bool znakstack::JeLiPun() const
{
return StackPointer == StackSize - 1 ? true : false;
}
bool znakstack::Uzmi(char& TopElem)
{
if (!JeLiPrazan())
{
TopElem = Element[StackPointer--];
return true;
}
else
{
cout << "Stek je prazan. Uzimanje nije obavljeno.\n";
return false;
}
}
bool znakstack::Ubaci(const char& NoviElem)
{
if (!JeLiPun())
{
Element[++StackPointer] = NoviElem;
return true;
}
else
{
cout << "Stek je pun. Ubacivanje nije obavljeno.\n";
return false;
}

}
Main.cpp
#include "znakstack.h"
int main()
{
znakstack ZnakStack(30);
char znak,l;
cout << "Unesite neki string: ";
cin.get(znak);
while (znak != '\n')
{
ZnakStack.Ubaci(znak);
cin.get(znak);
}
cout << "Obrnuti string: ";
while (!ZnakStack.JeLiPrazan())
{
ZnakStack.Uzmi(znak);
cout << znak;
}
cout << endl;
return 0;
}
RED
Intqueue.h
#include <iostream>
class intqueue
{
protected:
int QSize; // Size of the Element array
int *Element; // For storing queue contents
int Head, Tail; // Locate head and (tail+1)%QSize
public:
bool Empty() const;
bool Full() const;
intqueue(int queuesize = 10);
virtual ~intqueue();
virtual bool Remove(int& TopElem);
virtual bool Add(const int& NewElem);
};
Intqueue.cpp
#include "intqueue.h"
bool intqueue::Empty() const
{
return Head == Tail ? true : false;
}
bool intqueue::Full() const
{
return (Tail + 1) % QSize == Head ? true : false;
}
intqueue::intqueue(int queuesize) : QSize(queuesize), Element(new int[queuesize]), Head(0), Tail(0) {}
intqueue::~intqueue()
{
delete [] Element;
}
bool intqueue::Remove(int& TopElem)
{
if (!Empty())
{
TopElem = Element[Head];
Head = (Head + 1) % QSize;
return true;
}
else {
cout << "Queue empty: Remove failed.\n";
return false;
}
}
bool intqueue::Add(const int& NewElem)
{
if (!Full())
{
Element[Tail] = NewElem;
Tail = (Tail + 1) % QSize;
return true;
}
else
{
cout << "Queue full: Add failed.\n";
return false;
}

}
Testqueue.h
#include "intqueue.h"
class testqueue : public intqueue
{
public:
testqueue(int queuesize = 10);
void Print() const;
int Menu() const;
};
Testqueue.cpp
#include "testqueue.h"
using namespace std;
testqueue::testqueue(int queuesize) : intqueue(queuesize) {}
void testqueue::Print() const
{
if (Empty())
cout << "Red je prazan.\n";
else
for (int marker = Head; marker != Tail; marker = (marker + 1) % QSize)
cout << marker << ' ' <<Element[marker] << endl;
}
int testqueue::Menu() const
{
int Choice;
cout << "--------------------------\n";
cout << "Izaberite neku od ponudjenih opcija:\n";
cout << "1. Dodavanje cijelog broja u red\n";
cout << "2. Uklanjanje elementa iz reda\n";
cout << "3. Ispis sadrzaja reda na monitoru.\n";
cout << "0. Izlaz.\n";
cout << "Unesite Vas izbor: ";
cin >> Choice;
return Choice;
}
Queue.cpp
#include "testqueue.h"
using namespace std;
int main()
{
testqueue Queue(5);
int Choice, Item;
while (Choice = Queue.Menu())
switch(Choice) {
case 0:
return 0;
case 1:
cout << "Unesite cijeli broj: ";
cin >> Item;
Queue.Add(Item);
break;
case 2:
if (Queue.Remove(Item))
cout << "Element " <<Item << " je uklonjen.\n";
break;
case 3:
cout << "Sadrzaj reda je:\n";
Queue.Print();
break;
}
return 0;
}

LIFO Lista
Lifolist.h
#include <iostream>
class LinkedList
{
private:
struct node
{
int info;
node * next;
};
typedef node * nodeptr;
nodeptr start;
int count;
public:
LinkedList();
~LinkedList();
// Dodavanje cvora u povezanu Lifo listu.
void InsertLifo(int x); // Ispisuje vrijednosti iz cvorova.
void Print();
};
Lifolist.cpp
#include <iostream>
#include "ListLifo.h"
using namespace std;
LinkedList::LinkedList()
{
start = NULL;
count = 0;
}
LinkedList::~LinkedList()
{
nodeptr p = start, n;
while (p != NULL)
{
n = p;
p = p->next;
delete n;
}
}
void LinkedList::InsertLifo(int x)
{
nodeptr tmp;
tmp=start;
start = new node();
start->info = x;
start->next = tmp;
count++;
}
void LinkedList::Print()
{
nodeptr p = start;
while (p != NULL)
{
cout << p->info << endl;
p = p->next;
}
}
Testlifo.cpp
#include <iostream>
#include "listlifo.h"
int main()
{
LinkedList list1 ;
list1.InsertLifo(25);
list1.InsertLifo(14);
list1.InsertLifo(32);
list1.InsertLifo(7);
cout << "Pocetni sadrzaj liste je:" << endl;
list1.Print();
// dodajemo jos nekoliko elemenata
list1.InsertLifo( 20 );
list1.InsertLifo( 30 );
cout << "Sadrzaj liste nakon dodavanja je:" << endl;
list1.Print();
return 0;

}
FIFO Lista
Listfifo.h
#include <iostream>
class LinkedList
{
private:
struct node
{
int info;
node * next;
};
typedef node * nodeptr;
nodeptr start;
nodeptr last;
int count;
public:
LinkedList();
~LinkedList();
void InsertFifo(int x);
void Print();
};
Listfifo.cpp
#include <iostream>
#include "listfifo.h"
using namespace std;
LinkedList::LinkedList()
{
start = NULL;
count = 0;
}
LinkedList::~LinkedList()
{
nodeptr p = start, n;
while (p != NULL)
{
n = p;
p = p->next;
delete n;
}
}
void LinkedList::InsertFifo(int x)
{
nodeptr tmp;
if(start==NULL)
{
start=new node();
start->info = x;
start->next=NULL;
last=start;
}
else
{
last->next= new node();
last=last->next;
last->info=x;
last->next = NULL;
}
count++;
}
void LinkedList::Print()
{
nodeptr p = start;
while (p != NULL)
{
cout << p->info << endl;
p = p->next;
}
}

// Dodavanje cvora u povezanu Lifo listu.


// Ispisuje vrijednosti iz cvorova.

Testfifo.cpp
#include <iostream>
#include "listfifo.h"
using namespace std;
int main()
{
LinkedList list1 ;
list1.InsertFifo(26);
list1.InsertFifo(16);
list1.InsertFifo(31);
list1.InsertFifo(8);
cout << "Pocetni sadrzaj liste je:" << endl;
list1.Print();
// dodajemo jos nekoliko elemenata
list1.InsertFifo( 25 );
list1.InsertFifo( 35 );
cout << "Sadrzaj liste nakon dodavanja je:" << endl;
list1.Print();
return 0;
}
SORTIRANA LISTA
Listsort.h
#include <iostream>
class LinkedList
{
private:
struct node
{
int info;
node * next;
};
typedef node * nodeptr;
nodeptr start;
int count;
public:
LinkedList();
~LinkedList();
// Dodavanje cvora u povezanu listu tako da lista ostaje sortirana
// u rastucem smjeru.
void InsertSort(int x);
// Brisanje prvog cvora sa vrijednoscu x, ako takav cvor postoji.
void DeleteNode(int x);
// Ispisuje vrijednosti iz cvorova.
void Print();
// Vraca broj cvorova u listi.
int Size();
};
Listsort.cpp
#include <iostream>
#include "listsort.h"
using namespace std;
LinkedList::LinkedList()
{
start = NULL;
count = 0;
}
LinkedList::~LinkedList()
{
nodeptr p = start, n;
while (p != NULL)
{
n = p;
p = p->next;
delete n;
}
}
void LinkedList::InsertSort(int x)
{
nodeptr n, prev, curr;
n = new node;
n->info = x;
count++;
if (start == NULL)
{
start = n;
n->next = NULL;

}
else
{
curr = start;
while (curr != NULL && x>curr->info)
{
prev = curr;
curr = curr->next;
}
if (curr == start)
{
n -> next = start;
start = n;
}
else
{
prev->next = n;
n -> next = curr;
}
}
}
void LinkedList::DeleteNode(int x)
{
nodeptr prev, curr;
curr = start;
while (curr != NULL && x > curr->info)
{
prev = curr;
curr = curr->next;
}
if (x == curr->info)
{
if ( curr == start )
start = start->next;
else
prev->next = curr->next;
delete curr;
count--;
}
}
void LinkedList::Print()
{
nodeptr p = start;
while (p != NULL)
{
cout << p->info << endl;
p = p->next;
}
}
int LinkedList::Size()
{
return count;
}
Testsort.cpp
#include <iostream>
#include "listsort.h"
using namespace std;
int main()
{
int a;
LinkedList list1 ;
list1.InsertSort(25);
list1.InsertSort(14);
list1.InsertSort(32);
list1.InsertSort(7);
cout << "Pocetni sadrzaj liste je:" << endl;
list1.Print();
cout << "Velicina liste je:" << list1.Size()<<endl;
// dodajemo jos nekoliko elemenata
list1.InsertSort( 20 );
list1.InsertSort( 30 );
cout << "Sadrzaj liste nakon dodavanja je:" << endl;
list1.Print();
cout << "Velicina liste je:" << list1.Size()<<endl;
// brisemo nekoliko elemenata
list1.DeleteNode( 7 );
cout << "Sadrzaj liste nakon brisanja je:" << endl;
list1.Print();
cout << "Velicina liste je:" << list1.Size()<<endl;
cin>>a;
return 0;
}

FIFO Lista sa Fiktivnim Cvorom


Lists.h
#include<iostream>
using namespace std;
template <class Type>
class list
{
protected:
struct ListNode
{
Type Element;
ListNode *Next;
ListNode() : Next(0) {}
ListNode(Type Data, ListNode *Node = 0) :
Element(Data), Next(Node) {}
};
ListNode *Head;
Type DefaultVal;
public:
list() : Head(new ListNode) {}
list(Type defaultval) : DefaultVal(defaultval), Head(new ListNode) {}
virtual ~list();
bool Empty() const;
virtual void Insert(const Type& NewElement);
virtual bool DeleteElement(const Type& DelElement);
void Print() const;
void Read();
};
Listtemp.h
#include "lists.h"
template <class Type>
list<Type>::~list()
{
ListNode *Temp = Head->Next;
while (Temp)
{
Head->Next = Temp->Next;
delete Temp;
Temp = Head->Next;
}
delete Head;
}
template <class Type>
bool list<Type>::Empty() const
{
return Head->Next == 0 ? TRUE : FALSE;
}
// Dodaje novi element na kraj liste
template <class Type>
void list<Type>::Insert(const Type& NewElement)
{
ListNode *Marker;
for(Marker = Head; Marker->Next;Marker = Marker->Next);
Marker->Next = new ListNode(NewElement, Marker->Next);
}
template <class Type>
bool list<Type>::DeleteElement(const Type& DelElement)
{
ListNode *Marker = Head, *Temp;
for(; Marker->Next && Marker->Next->Element != DelElement;Marker = Marker->Next);
if ((Temp = Marker->Next) && Marker->Next->Element == DelElement)
{
Marker->Next = Marker->Next->Next;
delete Temp;
return true;
}
else
return false;
}
template <class Type>
void list<Type>::Print() const
{
cout << "Sadrzaj FIFO liste: ";
ListNode *Marker = Head->Next;
for (; Marker; Marker = Marker->Next)
cout << Marker->Element << ' ';
cout << endl;
}

template <class Type>


void list<Type>::Read()
{
Type NewElement;
cout << "Unesite elemente liste. Za kraj unosa unesite "<< DefaultVal << "\n";
cout << "Unesite element: ";
cin >> NewElement;
while (NewElement != DefaultVal)
{
Insert(NewElement);
cout << "Unesite element: ";
cin >> NewElement;
}
}
Main.cpp
#include "listtemp.h"
int main()
{
list<int> TestList(0);
int DelElement;
TestList.Read();
TestList.Print();
cout << "Izbacujemo 3 elementa.\n";
for (int i=0; i<3; i++)
{
cout << "Koji element treba izbaciti: ";
cin >> DelElement;
if (TestList.DeleteElement(DelElement))
cout << "Element je obrisan.\n";
else
cout << "Element nije u listi.\n";
}
TestList.Print();
return 0;
}
INSERTIONSORT
Datalist.h // Isto kao datalist.h u binarnom pretrazivanju
Datatemp.h//Isto kao datatemp.h u binarnom pretrazivabju
Insertion.h
#include "datalist.h"
using namespace std;
template <class Type>
class InsertSortList : public datalist<Type>
{
public:
InsertSortList(int arraysize = 10) : datalist<Type>(arraysize) {}
virtual ~InsertSortList() {}
virtual void Sort();
};
Instm.h
#include "insertion.h"
#include "datatemp.h"
using namespace std;
template <class Type>
void InsertSortList<Type>::Sort()
{
Type temp;
int marker1, marker2;
for(marker1 = 1; marker1 < ArraySize; marker1++)
{
if (Element[marker1] < Element[marker1 - 1])
{
temp = Element[marker1];
for (marker2 = marker1 - 1; marker2 >= 0; marker2--)
{
Element[marker2 + 1] = Element[marker2];
if (marker2 == 0 || Element[marker2 - 1] < temp)
break;
}
Element[marker2] = temp;
}
}

}
Insertion.cpp
#include "instm.h"
const int SIZE = 10;
int main()
{
InsertSortList<int> TestInsertSort(SIZE);
cin >> TestInsertSort;
cout << "Provjeravamo Insertion Sort:\n"<< TestInsertSort;
TestInsertSort.Sort();
cout << "Nakon sortiranja:\n" << TestInsertSort;
int a;
cin>>a;
return 0;
}
SELECTIONORT
Datalist.h
Datatemp.h // Isto kao kod binarnog pretrazivanja
Selection.h
#include "datalist.h"
template <class Type>
class SelectSortList : public datalist<Type>
{
protected:
void Swap(const int marker1, const int marker2);
int MaxKey(const int low, const int high);
public:
SelectSortList(int arraysize = 10) : datalist<Type>(arraysize) {}
virtual ~SelectSortList() {}
virtual void Sort();
};
Selectiontm.h
#include "selection.h"
#include "datatemp.h"
template <class Type>
void SelectSortList<Type>::Swap(const int marker1, const int marker2)
{
Type temp;
temp = Element[marker1];
Element[marker1] = Element[marker2];
Element[marker2] = temp;
}
template <class Type>
int SelectSortList<Type>::MaxKey(const int low, const int high)
{
int marker1, max = low;
for (marker1 = low + 1; marker1 <= high; marker1++)
if (Element[max] < Element[marker1])
max = marker1;
return max;
}
template <class Type>
void SelectSortList<Type>::Sort()
{
int marker1, marker2;
for (marker1 = ArraySize - 1; marker1 > 0; marker1--)
{
marker2 = MaxKey(0, marker1);
Swap(marker2, marker1);
}
}
Selection.cpp
#include "selectiontm.h"
const int SIZE = 10;
int main()
{
SelectSortList<int> TestSelectSort(SIZE);
cin >> TestSelectSort;
cout << "Provjeravamo Selection sortiranje:\n"<< TestSelectSort;
TestSelectSort.Sort();
cout << "Nakon sortiranja sadrzaj je:\n" << TestSelectSort;
int a;
cin>>a;
return 0;
}

MERGESORT
Datalist.h
Datatemp.h // Isto kao kod binarnog pretrazivanja
Merge.h
#include "datalist.h"
template <class Type>
class MergeSortList : public datalist<Type>
{
protected:
void MergeSort(Type *temp, const int list1, const int size);
void Merge(Type *temp, const int list1, const int size1, const int list2, const int size2);
public:
MergeSortList(int arraysize = 10) : datalist<Type>(arraysize) {}
virtual ~MergeSortList() {}
virtual void Sort();
};
Mergetmp.h
#include "merge.h"
#include "datatemp.h"
template <class Type>
void MergeSortList<Type>::MergeSort(Type *temp, const int list1, const int size)
{
int list2, size1, size2;
if (size > 1)
{
list2 = list1 + size / 2;
size1 = list2 - list1;
size2 = size - size1;
MergeSort(temp, list1, size1);
MergeSort(temp, list2, size2);
Merge(temp, list1, size1, list2, size2);
}
}
template <class Type>
void MergeSortList<Type>::Merge(Type *temp, const int list1, const int size1, const int list2, const int size2)
{
int i = list1, j = list2, k = list1;
while(i < list1 + size1 && j < list2 + size2)
{
if (temp[i] < temp[j])
Element[k++] = temp[i++];
else
Element[k++] = temp[j++];
}
while (i < list1 + size1)
Element[k++] = temp[i++];
while (j < list2 + size2)
Element[k++] = temp[j++];
for (k = list1; k < list1 + size1 + size2; k++)
temp[k] = Element[k];
}
template <class Type>
void MergeSortList<Type>::Sort()
{
Type *temp = new Type[ArraySize];
for(int i = 0; i < ArraySize; i++)
temp[i] = Element[i];
MergeSort(temp, 0, ArraySize);
delete [] temp;
}
Main.cpp
#include "mergetmp.h"
using namespace std;
const int SIZE = 10;
int main()
{
MergeSortList<int> TestMergeSort(SIZE);
cin >> TestMergeSort;
cout << "Provjeravamo algoritam-Merge Sort:\n" << TestMergeSort;
TestMergeSort.Sort();

cout << "Nakon sortiranja:\n" << TestMergeSort;


return 0;
}
LIFO Lista sa Fiktivnim Cvorom
Listlifo.h
#include<iostream>
template <class Type>
class list
{
protected:
struct ListNode
{
Type Element;
ListNode *Next;
ListNode() : Next(0) {}
ListNode(Type Data, ListNode *Node = 0) :
Element(Data), Next(Node) {}
};
ListNode *Head;
Type DefaultVal;
public:
list() : Head(0) {}
list(Type defaultval) : DefaultVal(defaultval), Head(0) {}
virtual ~list();
bool Empty() const;
virtual void Insert(const Type& NewElement);
virtual bool DeleteElement(const Type& DelElement);
void Print() const;
void Read();
};
Listemp.h
#include "listlifo.h"
using namespace std;
template <class Type>
list<Type>::~list()
{
ListNode *Temp = Head->Next;
while (Temp)
{
Head->Next = Temp->Next;
delete Temp;
Temp = Head->Next;
}
delete Head;
}
template <class Type>
bool list<Type>::Empty() const
{
return Head->Next == 0 ? TRUE : FALSE;
}
//Dodaje NoviElement na kraj liste
template <class Type>
void list<Type>::Insert(const Type& NewElement)
{
ListNode *Marker;
Marker=Head;
Head=new ListNode(NewElement, Marker);
}
template <class Type>
bool list<Type>::DeleteElement(const Type& DelElement)
{
ListNode *Marker = Head, *Temp=NULL;
for(; Marker&& Marker->Element != DelElement;Marker = Marker->Next)
Temp=Marker;
if (Marker!=NULL&&Temp!=NULL)
{
Temp->Next = Marker->Next;
delete Marker;
return true;
}
else if (Marker!=NULL&&Temp==NULL)
{
Head=Marker->Next;
delete Marker;
return true;

}
else
return false;
}
template <class Type>
void list<Type>::Print() const
{
cout << "Ispisujemo elemente liste: ";
ListNode *Marker = Head;
for (; Marker; Marker = Marker->Next)
cout << Marker->Element << ' ';
cout << endl;
}
template <class Type>
void list<Type>::Read()
{
Type NewElement;
cout << "Unesite elemente liste. Za kraj liste unesite "<< DefaultVal << "\n";
cout << "Unesite element liste: ";
cin >> NewElement;
while (NewElement != DefaultVal)
{
Insert(NewElement);
cout << "Unesite element liste: ";
cin >> NewElement;
}
}
Main.cpp
#include "listtemp.h"
using namespace std;
int main()
{
list<int> TestList(0);
int DelElement;
TestList.Read();
TestList.Print();
cout << "Sada izbacujemo nekolko elemenata u tri pokusaja.\n";
for (int i=0; i<3; i++)
{
cout << "Koji element zelite izbaciti: ";
cin >> DelElement;
if (TestList.DeleteElement(DelElement))
cout << "Element je obrisan.\n";
else
cout << "Element nije u listi.\n";
}
TestList.Print();
return 0;
}
QUICKSORT
Datalist.h
Datatemp.h // Isto kao kod binarnog pretrazivanja
Quick.h
#include "datalist.h"
using namespace std;
template <class Type>
class QuickSortList : public datalist<Type>
{
protected:
void Swap(const int i, const int j);//Funkcija za zamjenu dva elementa.
int Partition(const int low, const int high);//Funkcija za podjelu liste.
void QuickSort(const int low, const int high);//Funkcija za sortiranje.
public:
QuickSortList(int arraysize = 10) : datalist<Type>(arraysize) {}
virtual ~QuickSortList() {}
virtual void Sort();
};
Quicktemp.h
#include "quick.h"
#include "datatemp.h"
using namespace std;
template <class Type>
void QuickSortList<Type>::Swap(const int i,const int j)
{
Type temp = Element[i];

Element[i] = Element[j];
Element[j] = temp;
}

template <class Type>


int QuickSortList<Type>::Partition(const int low, const int high)
{
int pivotloc, i;
Type pivotkey;
pivotkey = Element[low];
pivotloc = low;
for (i = low + 1; i <= high; i++)
if (Element[i] < pivotkey)
Swap(++pivotloc, i); //alta pokazivace, a ne elemente
Swap(low, pivotloc); //radi kad se zavrsi for
return pivotloc;
}
template <class Type>
void QuickSortList<Type>::QuickSort(const int low, const int high)
{
int pivotloc;
if (low < high)
{
pivotloc = Partition(low, high);
QuickSort(low, pivotloc - 1);
QuickSort(pivotloc + 1, high);
}
}
template <class Type>
void QuickSortList<Type>::Sort()
{
QuickSort(0, ArraySize - 1);
}
Main.cpp
#include "quicktmp.h"
using namespace std;
const int SIZE = 10;
int main()
{
QuickSortList<int> TestQuickSort(SIZE);
cin >> TestQuickSort;
cout << "Provjeravamo Quick Sort:\n" << TestQuickSort;
TestQuickSort.Sort();
cout << "Nakon sortiranja:\n" << TestQuickSort;
return 0;
}
BINARNO STABLO
Bintree.h
#include <iostream>
using namespace std;
template <class Type>
class bintree {
public:
struct treenode
{
Type Element;
treenode *left, *right;
treenode() : left(0), right(0) {}
treenode(Type item, treenode *leftnode=0,treenode *rightnode=0):
Element(item), left(leftnode),right(rightnode) {}
};
protected:
treenode *root;
Type RefValue;
bool Insert(treenode* &tree, const Type& item);
void Traverse(treenode *tree, ostream& out) const;
bool Search(treenode* tree, const Type& item) const;
void destroy(treenode *tree);
public:
bintree() : root(0) {}
bintree(Type refvalue) : RefValue(refvalue),root(0) {}
virtual ~bintree();
virtual bool Insert(const Type& item);
virtual bool Search(const Type& item) const;
virtual bool Delete(const Type& item);
friend istream& operator>><>(istream& in,bintree<Type>& Tree);
friend ostream& operator<<<>(ostream& out, const bintree<Type>& Tree);
};

Bintemp.h
#include "bintree.h"
template <class Type>
bool bintree<Type>::Insert(treenode* &tree,const Type& item)
{
if (tree == 0)
{
tree = new treenode(item);
return tree ? true : false;
}
else if (item < tree->Element)
return Insert(tree->left, item);
else
return Insert(tree->right, item);
}
template <class Type>
void bintree<Type>::Traverse(treenode *tree,ostream& out) const
{
if (tree)
{
Traverse(tree->left, out);
out << tree->Element << ' ';
Traverse(tree->right, out);
}
}
template <class Type>
bool bintree<Type>::Search(treenode* tree,const Type& item) const
{
if (tree)
{
if (tree->Element == item)
return true;
else if (item < tree->Element)
return Search(tree->left, item);
else
return Search(tree->right, item);
}
return false;
}
template <class Type>
void bintree<Type>::destroy(treenode *tree)
{
if (tree)
{
destroy(tree->left);
destroy(tree->right);
delete tree;
}
}
template <class Type>
bintree<Type>::~bintree()
{
destroy(root);
}
template <class Type>
bool bintree<Type>::Insert(const Type& item)
{
return Insert(root, item);
}
template <class Type>
bool bintree<Type>::Search(const Type& item) const
{
return Search(root, item);
}
template <class Type>
istream& operator>>(istream& in, bintree<Type>& Tree)
{
Type item;
cout << "Construct binary tree:\n";
cout << "Input element (end with " <<Tree.RefValue << "): ";
in >> item;
while (item != Tree.RefValue)
{
Tree.Insert(item);
cout << "Input element (end with " <<Tree.RefValue << "): ";
in >> item;
}
return in;

template <class Type>


ostream& operator<<(ostream& out,const bintree<Type>& Tree)
{
out << "Inorder traversal of binary tree.\n";
Tree.Traverse(Tree.root, out);
out << endl;
return out;
}
template <class Type>
bool bintree<Type>::Delete(const Type& item)
{
treenode *marker=root, *parent=0, *child=root;
treenode *temp;
while (marker && marker->Element != item)
{
parent = marker;
if (item < marker->Element)
marker = marker->left;
else
marker = marker->right;
}
if (!marker)
return false;
if (!parent)
{ // Delete root node
if (!marker->right)
root = marker->left;
else if (!marker->left)
root = marker->right;
else {
for (temp = marker, child = marker->left;child->right;temp = child, child = child->right);
if (child != marker->left)
{
temp->right = child->left;
child->left = root->left;
}
child->right = root->right;
root = child;
}
}
else if (!marker->right)
{
if (parent->left == marker)
parent->left = marker->left;
else
parent->right = marker->left;
}
else if (!marker->left)
{
if (parent->left == marker)
parent->left = marker->right;
else
parent->right = marker->right;
}
else {
for (temp = marker,child = marker->left;child->right;temp = child, child = child->right);
if (child != marker->left)
{
temp->right = child->left;
child->left = marker->left;
}
child->right = marker->right;
if (parent->left == marker)
parent->left = child;
else
parent->right = child;
}
delete marker;
return true;
}

Bintree.cpp
#include "bintemp.h"
int main()
{
bintree<int> TestTree(0);
int TestItem;
cin >> TestTree;
cout << TestTree;
cout << "Delete some items. (End with 0): ";
cin >> TestItem;
while (TestItem)
{
cout << "Item " <<(TestTree.Delete(TestItem) ? " " : "not ")<< "found.\n";
cout << "Enter element: ";
cin >> TestItem;
}
cout << TestTree;
return 0;
}
HESIRANJE SA OTVORENIM ADRESIRANJEM
Openadd.h
#include <iostream>
using namespace std;
template <class Type>
class openAddress
{
protected:
Type *Element;
Type EmptyCell;
int TableSize;
virtual int HashFunc(const Type& Item) const = 0;
public:
openAddress(int tablesize = 1000);
openAddress(Type emptycell, int tablesize = 1000);
~openAddress();
virtual bool Store(const Type& Item);
virtual bool Retrieve(const Type& SearchItem,Type& FoundItem) const;
};
Opentmp.h
#include "openadd.h"
template <class Type>
openAddress<Type>::openAddress(int tablesize) :TableSize(tablesize), Element(new Type[tablesize]){}
template <class Type>
openAddress<Type>::openAddress(Type emptycell, int tablesize) :TableSize(tablesize), Element(new
Type[tablesize]),EmptyCell(emptycell)
{
for (int elem = 0; elem < TableSize; elem++)
Element[elem] = EmptyCell;
}
template <class Type>
openAddress<Type>::~openAddress()
{
delete [] Element;
}
template <class Type>
bool openAddress<Type>::Store(const Type& Item)
{
int index = HashFunc(Item);
for (int probe = 0; probe < TableSize; ++probe)
{
if (Element[index] == EmptyCell)
{
Element[index] = Item;
return true; // Item inserted
}
else if (Element[index] == Item)
return false; // Item already in table
else
index = (index + 1) % TableSize;
}

return false; // Table full


}

template <class Type>


bool openAddress<Type>::Retrieve(const Type& SearchItem,Type& FoundItem) const
{
int index = HashFunc(SearchItem);
for (int probe = 0; probe < TableSize; ++probe)
{
if (Element[index] == SearchItem)
{
FoundItem = Element[index];
return true; // Item found
}
else
index = (index + 1) % TableSize;
}
return false;
}
Testlin.h
#include "opentmp.h"
class LinearIntProbe : public openAddress<long>
{
private:
int HashFunc(const long& Item) const;
public:
LinearIntProbe(long emptycell = 0,int tablesize = 1000) :
openAddress<long>(emptycell, tablesize) {}
};
Testlin.cpp
#include "testlin.h"
int LinearIntProbe::HashFunc(const long& Item) const
{
return Item % TableSize;
}
Linprobe.cpp
#include "testlin.h"
int main()
{
LinearIntProbe InTable(100);
long NewItem, GetItem, GotItem;
int i;
for (i = 0; i < 10; i++)
{
cout << "Upisite cjelobrojnu vrijednost za unos u tabelu: ";
cin >> NewItem;
if (InTable.Store(NewItem))
cout << "Element je pohranjen.\n";
else
cout << "Element je vec u tabeli.\n";
}
for (i = 0; i < 4; i++)
{
cout << "Upisite cjelobrojnu vrijednost koju dohvacamo iz tabele: ";
cin >> GetItem;
if (InTable.Retrieve(GetItem, GotItem))
cout << "Element " << GotItem << " je pronadjen.\n";
else
cout << "Element nije pronaen.\n";
}
return 0;
}
HESIRANJE SA ULANCAVANJEM
Lists.h
Listtemp.h // Isto kao kod FIFO lista sa fiktivnim cvorem
#include "lists.h"
template <class Type>
class chainList : public list<Type>
{
public:
chainList() : list<Type>() {}
bool Search(const Type& SearchElement) const;
bool Search(const Type& SearchElement, Type& FoundElement) const;
};
template <class Type>

class chainTable
{
protected:
chainList<Type> *Bucket;
int TableSize;
virtual int HashFunc(const Type& Item) const = 0;
public:
chainTable(int tablesize = 1000);
virtual ~chainTable();
virtual bool Store(const Type& Item);
virtual bool Retrieve(const Type& SearchItem,Type& FoundItem) const;
};
Chaintmp.h
#include "chaining.h"
#include "listtemp.h"
template <class Type>
bool chainList<Type>::Search(const Type& SearchElement) const
{
ListNode *Marker;
for (Marker = Head->Next;Marker && Marker->Element != SearchElement;Marker = Marker->Next);
return (Marker ? true : false);
}
template <class Type>
bool chainList<Type>::Search(const Type& SearchElement,Type& FoundElement) const
{
ListNode *Marker;
for (Marker = Head->Next;Marker && Marker->Element != SearchElement;Marker = Marker->Next);
if (Marker)
{
FoundElement = Marker->Element;
return true;
}
else
{
FoundElement = SearchElement;
return false;
}
}
template <class Type>
chainTable<Type>::chainTable(int tablesize) : TableSize(tablesize), Bucket(new chainList<Type>[tablesize]){}
template <class Type>
chainTable<Type>::~chainTable()
{
delete [] Bucket;
}
template <class Type>
bool chainTable<Type>::Store(const Type& Item)
{
int index = HashFunc(Item);
if (Bucket[index].Search(Item))
return false;
Bucket[index].Insert(Item);
return true;
}
template <class Type>
bool chainTable<Type>::Retrieve(const Type& SearchItem,Type& FoundItem) const
{
int index = HashFunc(SearchItem);
return Bucket[index].Search(SearchItem, FoundItem) ? true : false;
}
Chaintst.h
#include<iostream>
#include "chaining.h"
#include "chaintmp.h"
class chainInt : public chainTable<long>
{
private:
int HashFunc(const long& Item) const;
public:
chainInt(int tablesize = 1000) :
chainTable<long>(tablesize) {}
}
Chaintst.h
#include<iostream>
#include "chaintst.h"
int chainInt::HashFunc(const long& Item) const
{
return Item % TableSize;
}

Chaining.cpp
#include<iostream>
#include "chaintst.h"
int main()
{
chainInt InTable(100);
long NewItem, GetItem, GotItem;
int i;
for (i = 0; i < 10; i++)
{
cout << "Unesite cijeli broj koji ide u tabelu: ";
cin >> NewItem;
if (InTable.Store(NewItem))
cout << "Element je smjesten.\n";
else
cout << "Element je vec u tabeli.\n";
}
for (i = 0; i < 4; i++)
{
cout << "Unesite cijeli broj koji se pronalazi iz tabele: ";
cin >> GetItem;
if (InTable.Retrieve(GetItem, GotItem))
cout << "Element " << GotItem << " je pronadjen.\n";
else
cout << "Element nije pronadjen.\n";
}
return 0;
}
AVL Stablo
Avltree.h
#include <iostream>
using namespace std;
enum {LEFTHIGH, BALANCED, RIGHTHIGH};
template <class Type>
class avltree
{
public:
struct avlnode
{
Type Element;
avlnode *left, *right;
int balance;
avlnode() : left(0), right(0), balance(BALANCED) {}
avlnode(Type item, avlnode *leftnode=0,avlnode *rightnode=0) : Element(item), left(leftnode),
right(rightnode),balance(BALANCED) {}
};
protected:
Type RefValue;
avlnode *root;
bool Insert(avlnode* &tree, Type item, bool& taller);
void RotateLeft(avlnode *Tree, avlnode* &NewTree);
void RotateRight(avlnode *Tree, avlnode* &NewTree);
void LeftBalance(avlnode* &Tree, bool& taller);
void RightBalance(avlnode* &Tree, bool& taller);
void Traverse(avlnode *Tree, ostream& out) const;
int Depth(avlnode *Tree) const;
public:
avltree() : root(0) {}
avltree(Type refvalue) : RefValue(refvalue), root(0) {}
bool Insert(Type item)
{
bool taller;
return Insert(root, item, taller);
}
friend istream& operator>><>(istream& in,avltree<Type>& Tree);
friend ostream& operator<<<>(ostream& out,const avltree<Type>& Tree);
int Depth() const;
};

Avlbal.h
#include "avltree.h"
template <class Type>
void avltree<Type>::LeftBalance(avlnode* &Tree,bool& taller)
{
avlnode *leftsub = Tree->left;
avlnode *rightsub;
switch(leftsub->balance)
{
case LEFTHIGH:
Tree->balance = leftsub->balance = BALANCED;
RotateRight(Tree, Tree);
taller = false;
break;
case BALANCED:
cout <<
"LeftBalance error: Tree already balanced.\n";
break;
case RIGHTHIGH:
rightsub = leftsub->right;
switch(rightsub->balance)
{
case LEFTHIGH:
Tree->balance = RIGHTHIGH;
leftsub->balance = BALANCED;
break;
case BALANCED:
Tree->balance = leftsub->balance = BALANCED;
break;
case RIGHTHIGH:
Tree->balance = BALANCED;
leftsub->balance = LEFTHIGH;
break;
}
rightsub->balance = BALANCED;
RotateLeft(leftsub, Tree->left);
RotateRight(Tree, Tree);
taller = false;
}
}
template <class Type>
void avltree<Type>::RightBalance(avlnode* &Tree,bool& taller)
{
avlnode *rightsub = Tree->right;
avlnode *leftsub;
switch(rightsub->balance)
{
case RIGHTHIGH:
Tree->balance = rightsub->balance = BALANCED;
RotateLeft(Tree, Tree);
taller = false;
break;
case BALANCED:
cout <<"RightBalance error: Tree already balanced.\n";
break;
case LEFTHIGH:
leftsub = rightsub->left;
switch(leftsub->balance)
{
case RIGHTHIGH:
Tree->balance = LEFTHIGH;
rightsub->balance = BALANCED;
break;
case BALANCED:
Tree->balance = rightsub->balance = BALANCED;
break;
case LEFTHIGH:
Tree->balance = BALANCED;
rightsub->balance = RIGHTHIGH;
break;
}
leftsub->balance = BALANCED;
RotateRight(rightsub, Tree->right);
RotateLeft(Tree, Tree);
taller = false;
}
}

Avlins.h
#include "avltree.h"
template <class Type>
bool avltree<Type>::Insert(avlnode* &tree,Type item, bool& taller)
{
bool success;
if(!tree)
{
tree = new avlnode(item);
success = tree ? true : false;
if (success)
taller = true;
}
else if (item < tree->Element)
{
success = Insert(tree->left, item, taller);
if (taller)
switch(tree->balance)
{
case LEFTHIGH:
LeftBalance(tree,taller);
break;
case BALANCED:
tree->balance = LEFTHIGH;
break;
case RIGHTHIGH:
tree->balance = BALANCED;
taller = false;
break;
}
}
else
{
success = Insert(tree->right, item, taller);
if(taller)
switch(tree->balance)
{
case LEFTHIGH:
tree->balance = BALANCED;
taller = false;
break;
case BALANCED:
tree->balance = RIGHTHIGH;
break;
case RIGHTHIGH:
RightBalance(tree, taller);
break;
}
}
return success;
}
Avlrot.h
#include "avltree.h"
template <class Type>
void avltree<Type>::RotateLeft(avlnode *Tree,avlnode* &NewTree)
{
NewTree = Tree->right;
Tree->right = NewTree->left;
NewTree->left = Tree;
}
template <class Type>
void avltree<Type>::RotateRight(avlnode *Tree,avlnode* &NewTree)
{
NewTree = Tree->left;
Tree->left = NewTree->right;
NewTree->right = Tree;
}
Avltemp.h
#include
#include
#include
#include
#include

"avlins.h"
"avlrot.h"
"avlio.h"
"avlbal.h"
"avldepth.h"

Avlio.h
#include "avltree.h"
template <class Type>
istream& operator >> <>(istream& in, avltree<Type>& Tree)
{
Type item;
cout << "Izgradnja AVL stabla:\n";
cout << "Unesite cjelobrojni element (zavrsite sa " <<Tree.RefValue << "): ";
in >> item;
while (item != Tree.RefValue)
{
Tree.Insert(item);
cout << "Ulazni element (zavrsite sa " <<Tree.RefValue <<") ";
in >>item;
}
return in;
}
template <class Type>
void avltree<Type>::Traverse(avlnode *Tree,ostream& out) const
{
if (Tree)
{
Traverse(Tree->left,out);
out << Tree->Element << ' ';
Traverse(Tree->right,out);
}
}
template <class Type>
ostream& operator << <>(ostream& out,const avltree<Type>& Tree)
{
out << "Inorder prolaz kroz AVL stablo.\n";
Tree.Traverse(Tree.root, out);
out << endl;
return out;
}
Avldepth.h
#include "avltree.h"
template <class Type>
int avltree<Type>::Depth(avlnode *Tree) const
{
if (Tree)
{
int LeftDepth = Depth(Tree->left);
int RightDepth = Depth(Tree->right);
return 1+ (LeftDepth > RightDepth ? LeftDepth :
RightDepth);
}
else
{
return 0;
}
}
template <class Type>
int avltree<Type>::Depth() const
{
return Depth(root);
}
Avltree.cpp
#include "avltemp.h"
int main()
{
avltree<int> TestAVL(0);
cin >> TestAVL;
cout << TestAVL;
cout << "Dubina AVL stabla: " << TestAVL.Depth()<< endl;
return 0;
}

HEAPSORT
Heap.h
#include <iostream>
using namespace std;
template <class Type>
class heap
{
protected:
Type *Item;
int HeapSize;
virtual void Insert(Type NewItem, int start, int maxheap);
public:
heap(int heapsize = 10);
virtual ~heap();
virtual void MakeHeap();
virtual void Sort();
friend istream& operator>><>(istream& in, heap<Type>& InHeap);
friend ostream& operator<<<>(ostream& out, const heap<Type>& OutHeap);
};
Heaptmp.h
#include "heap.h"
template <class Type>
heap<Type>::heap(int heapsize) : HeapSize(heapsize),Item(new Type[heapsize+1]){}
template <class Type>
heap<Type>::~heap()
{
delete [] Item;
}
template <class Type>
void heap<Type>::MakeHeap()
{
for (int i = HeapSize/2; i >= 1; i--)
Insert(Item[i], i, HeapSize);
}
template <class Type>
void heap<Type>::Insert(Type NewItem, int start, int maxheap)
{
int marker = 2*start;
while(marker <= maxheap)
{
if (marker < maxheap && Item[marker] < Item[marker+1])
marker++;
if (NewItem >= Item[marker])
break;
else
{
Item[start] = Item[marker];
start = marker;
marker = 2*start;
}
}
Item[start] = NewItem;
}
template <class Type>
void heap<Type>::Sort()
{
Type TempItem;
int maxheap = HeapSize;
while (maxheap > 0)
{
TempItem = Item[maxheap];
Item[maxheap] = Item[1];
Insert(TempItem, 1, --maxheap);
}
}
template <class Type>
istream& operator>><>(istream& in, heap<Type>& InHeap)
{
cout << "Unesite " << InHeap.HeapSize <<" cjelobrojnih elemenata u gomilu:\n";
for (int i = 1; i <= InHeap.HeapSize; i++)
{
cout << "Element " << i << ": ";
in >> InHeap.Item[i];
}
InHeap.MakeHeap();
return in;

template <class Type>


ostream& operator<<<>(ostream& out, const heap<Type>& OutHeap)
{
for (int i = 1; i <= OutHeap.HeapSize; i++)
out << OutHeap.Item[i] << ' ';
return out;
}
Heap.cpp
#include "heaptmp.h"
int main()
{
heap<int> TestHeap(15);
cin >> TestHeap;
cout << "Pocetna gomila je:\n" << TestHeap << endl;
TestHeap.Sort();
cout << "Nakon sortiranja imamo:\n" << TestHeap << endl;
return 0;
}
BUBLESORT
Main.cpp
#include <iostream>
using namespace std;
#define BrEl 20
void bubbleSort(int brojevi[], int velicina)
{
int i, j, priv;
for (i = (velicina - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (brojevi[j-1] > brojevi[j])
{
priv = brojevi[j-1];
brojevi[j-1] = brojevi[j];
brojevi[j] = priv;
}
}
}
}
int main()
{
int A[BrEl]={25,14,7,76,10,64,20,30,9,2,6,77,83,12,56,46,61,51,33,26};
cout<<"NESORTIRANI NIZ:"<<endl;
for(int i=0;i<BrEl;i++)
{
cout<<A[i]<<endl;
}
bubbleSort(A,BrEl);
cout<<endl<<"SORTIRANI NIZ"<<endl;
for(int i=0;i<BrEl;i++)
{
cout<<A[i]<<endl;
}
return 0;
}
SHELLSORT
Main.cpp
#include <iostream>
#include <iomanip>
using namespace std;
#define BrEl 20
void shellSort (int a[], int n)
{
int i, j, k, h, v;
int cols[ ] = {7, 3,1};
for (int k=0; k<3; k++)
{
h=cols[k];
for (int i=h; i<n; i++)
{
v=a[i];
j=i;
while (j>=h && a[j-h]>v)
{
a[j]=a[j-h];

j=j-h;
}
a[j]=v;
}
}
}
int main()
{
int A[BrEl]={28,17,10,79,13,67,23,33,12,5,9,80,86,15,59,49,64,54,36,29},m;
cout<<"NESORTIRANI NIZ:"<<endl;
for(int i=0;i<BrEl;i++)
{
cout<<A[i]<<",";
}
cout<<endl;
shellSort(A,BrEl);
cout<<endl<<"SORTIRANI NIZ"<<endl;
for(int i=0;i<BrEl;i++)
{
cout<<A[i]<<",";
}
cout<<endl;
cin>>m;
return 0;
}
TOPOLOSKO SORTIRANJE
List.h
Listtemp.h // Isto kao kod lista
Queue.h
Qtemp.h // Isto kao kod reda
Listiter.h
#include "lists.h"
template <class Type>
class ListIterator;
template <class Type>
class linklist : public list<Type>
{
public:
linklist() : list<Type>() {}
linklist(Type defaultval) : list<Type>(defaultval) {}
friend ListIterator<Type>;
};
template <class Type>
class ListIterator
{
private:
linklist<Type> *LocalList;
typename list<Type>::ListNode *CurrentNode;
public:
ListIterator(linklist<Type> &List);
Type Next();
bool End();
};
Itertemp.h
#include "listiter.h"
#include "listtemp.h"
template <class Type>
ListIterator<Type>::ListIterator(linklist<Type> &List) :LocalList(&List), CurrentNode(List.Head){}
template <class Type>
Type ListIterator<Type>::Next()
{
if (!End())
CurrentNode = CurrentNode->Next;
return End() ? LocalList->DefaultVal : CurrentNode->Element;
}
template <class Type>
bool ListIterator<Type>::End()
{
return CurrentNode ? false : true;
}
Digraph.h
#include "itertemp.h"
#include <string>
#include <stdlib.h>
class digraph
{
protected:
linklist<int> *Edge;

int NumVertex;
public:
digraph(int numvertex = 10);
friend ostream& operator<<(ostream& OutStream, const digraph& OutGraph);
friend istream& operator>>(istream& InStream, digraph& InGraph);
};
Graph.h
#include "digraph.h"
digraph::digraph(int numvertex) :NumVertex(numvertex),Edge(new linklist<int>[numvertex]){}
istream& operator>>(istream& InStream, digraph& InGraph)
{
char line[80], *nextvertex;
int finish;
cout << "Za svaki cvor, unesite cvorove na koje je taj cvor spojen.\n";
for (int start = 0; start < InGraph.NumVertex; start++)
{
cout << "Cvor " << start << ": ";
InStream.getline(line, sizeof(line));
if (nextvertex = strtok(line, " "))
{
finish = atoi(nextvertex);
InGraph.Edge[start].Insert(finish);
while (nextvertex = strtok(0, " "))
{
finish = atoi(nextvertex);
InGraph.Edge[start].Insert(finish);
}
}
}
return InStream;
}
ostream& operator<<(ostream& OutStream, const digraph& OutGraph)
{
OutStream << "Lista cvorova i lukova.\n";
for (int start = 0; start < OutGraph.NumVertex; start++)
{
OutStream << "Cvor " << start << ": ";
ListIterator<int> Source(OutGraph.Edge[start]);
for (int Vertex = Source.Next(); !Source.End(); Vertex = Source.Next() )
OutStream << Vertex << ' ';
OutStream << endl;
}
return OutStream;
}
Topsort.h
#include "digraph.h"
#include "qtemp.h"
class topsort : public digraph
{
private:
int *TopOrder;
void Sort(int vertex, int& place, bool *visited);
public:
topsort(int numvertex = 10) :
digraph(numvertex), TopOrder(new int[numvertex]) {}
void DepthSort();
void BreadthSort();
void PrintTopSort();
}
Topfunc.cpp
#include "topsort.h"
void topsort::Sort(int Vertex, int& place, bool *visited)
{
ListIterator<int> temp(Edge[Vertex]);
visited[Vertex] = true;
for (int NextVertex = temp.Next();!temp.End(); NextVertex = temp.Next() )
if (!visited[NextVertex])
Sort(NextVertex,place,visited);
TopOrder[--place] = Vertex;
}
void topsort::DepthSort()
{
bool *visited = (bool *)new int[NumVertex];
int Vertex;
int place;
for (Vertex = 0; Vertex < NumVertex; Vertex++)
visited[Vertex] = false;

place = NumVertex;
for (Vertex = 0; Vertex < NumVertex; Vertex++)
if (!visited[Vertex])
Sort(Vertex,place,visited);
delete [] visited;
}
void topsort::BreadthSort()
{
int *predecessorcount = new int[NumVertex];
queue<int> vertexq(NumVertex);
int Vertex, NextVertex, place, TempVertex;
for (Vertex = 0; Vertex < NumVertex; Vertex++)
predecessorcount[Vertex] = 0;
for (Vertex = 0; Vertex < NumVertex; Vertex++)
{
ListIterator<int> temp(Edge[Vertex]);
for (TempVertex = temp.Next(); !temp.End(); TempVertex = temp.Next())
predecessorcount[TempVertex]++;
}
for (Vertex = 0; Vertex < NumVertex; Vertex++)
if (!predecessorcount[Vertex]) vertexq.Add(Vertex);
place = 0;
while (!vertexq.Empty())
{
vertexq.Remove(Vertex);
TopOrder[place++] = Vertex;
ListIterator<int> temp(Edge[Vertex]);
for (NextVertex = temp.Next();!temp.End(); NextVertex = temp.Next())
{
predecessorcount[NextVertex]--;
if (!predecessorcount[NextVertex])
vertexq.Add(NextVertex);
}
}
delete [] predecessorcount;
}
void topsort::PrintTopSort()
{
cout << "Topolosko uredjenje:\n";
for (int i=0; i<NumVertex; i++)
cout << TopOrder [i] << ' ';
cout << endl;
}
Topsort.cpp
#include "topsort.h"
int main()
{
topsort TestGraph(10);
cin >> TestGraph;
cout << TestGraph;
TestGraph.DepthSort();
cout << "Depth first sort:\n";
TestGraph.PrintTopSort();
TestGraph.BreadthSort();
cout << "Breadth first sort:\n";
TestGraph.PrintTopSort();
return 0;
}

KRUSKALOV ALGORITAM
Lists.h
Listtemp.h
Listiter.h
Itertemp.h // Isto kao kod topoloskog sortiranja
Undigraf.h
#include
#include
#include
#include
#include

"itertemp.h"
<string>
<stdlib.h>
"settemp.h"
<limits.h>

class undigraph {
public:
struct WeightEdge
{
int start, finish, weight;
bool operator<(const WeightEdge& OtherEdge) const
{
return weight < OtherEdge.weight ? true : false;
}
bool operator!=(const WeightEdge& OtherEdge) const
{
return (start != OtherEdge.start || weight != OtherEdge.weight || finish != OtherEdge.finish)
? true : false;
}
bool operator==(const WeightEdge& OtherEdge) const
{
return (start == OtherEdge.start && weight == OtherEdge.weight && finish == OtherEdge.finish)
? true : false;
}
friend ostream& operator<<(ostream& OutStream, const WeightEdge& OutWeightEdge);
friend istream& operator>>(istream& InStream, WeightEdge& InWeightEdge);
};
protected:
linklist<WeightEdge> *Edge;
int NumVertex;
public:
undigraph(int numvertex = 10);
friend ostream& operator<<(ostream& OutStream, const undigraph& OutGraph);
friend istream& operator>>(istream& InStream, undigraph& InGraph);
};
class mincostgraph : public undigraph
{
protected:
linklist<WeightEdge> EdgeList;
void MakeEdgeList();
public:
mincostgraph(int numvertex = 10) : undigraph(numvertex) {}
void Kruskal();
};
Sets.h

#include<iostream>
template <class Type, int SetSize>
class set
{
private:
Type Element[SetSize];
Type EmptyElement;
int Cardinality;
public:
set();
set(Type emptyelement);
bool contains(const Type& member) const;
bool insert(const Type& element);
// Union
set<Type,SetSize>
operator+(const set<Type,SetSize>& Set2) const;
// Intersection
set<Type,SetSize>
operator*(const set<Type,SetSize>& Set2) const;
void Print() const;
void Read();

};

Settemp.h
#include "sets.h"
template <class Type, int SetSize>
set<Type,SetSize>::set() : Cardinality(0) {}
template <class Type, int SetSize>
set<Type,SetSize>::set(Type emptyelement) : Cardinality(0), EmptyElement(emptyelement) {}
// Use + operator for set union.
// Elements added to Union from *this and Set2
// using insertion sort
template <class Type, int SetSize>
set<Type,SetSize> set<Type,SetSize>::operator+(const set<Type,SetSize>& Set2) const
{
set<Type,SetSize> Union;
int marker1 = 0, marker2 = 0;
int UnionSize = 0;
while (marker1 < Cardinality && marker2 < Set2.Cardinality)
{
if (Element[marker1] < Set2.Element[marker2])
{
Union.insert(Element[marker1]);
marker1++; UnionSize++;
}
else if(Element[marker1] == Set2.Element[marker2])
{
Union.insert(Element[marker1]);
marker1++; marker2++; UnionSize++;
}
else
{
Union.insert(Set2.Element[marker2]);
marker2++; UnionSize++;
}
}
for (; marker1 < Cardinality; marker1++)
{
Union.insert(Element[marker1]);
UnionSize++;
}
for (; marker2 < Set2.Cardinality; marker2++)
{
Union.insert(Set2.Element[marker2]);
UnionSize++;
}
if (UnionSize > SetSize)
cout << "Error in Union: Union cardinality exceeds universal set size.\n";
return Union;
}
// Use * operator for set intersection.
// Elements added to Intsect from *this and
// Set2 using insertion sort
template <class Type, int SetSize>
set<Type,SetSize> set<Type,SetSize>::operator*(const set<Type,SetSize>& Set2) const
{
set<Type,SetSize> Intsect;
int marker1 = 0, marker2 = 0;
while (marker1 < Cardinality && marker2 < Set2.Cardinality)
{
if (Element[marker1] < Set2.Element[marker2])
{
marker1++;
}
else if(Element[marker1] == Set2.Element[marker2])
{
Intsect.insert(Element[marker1]);
marker1++; marker2++;
}
else
{
marker2++;
}
}
return Intsect;
}
// Tests if "member" is in the current set
template <class Type, int SetSize>
bool set<Type,SetSize>::contains(const Type& member) const
{

int marker;
for (marker=0; marker < Cardinality; marker++)
if (Element[marker] == member)
return true;
return false;
}
// Adds "element" to current set; settemp.h
// returns true if successful
template <class Type, int SetSize>
bool set<Type,SetSize>::insert(const Type& element)
{
if (! contains(element) && Cardinality < SetSize)
{
int marker = Cardinality;
while (marker > 0 && element < Element[marker-1])
{
Element[marker] = Element[marker-1];
--marker;
}
Element[marker] = element;
Cardinality++;
return true;
}
else
{
return false;
}
}
// Reads in set elements from keyboard
template <class Type, int SetSize>
void set<Type,SetSize>::Read()
{
Type NewElement; Cardinality = 0;
cout << "Enter elements, finish with " << EmptyElement << endl << "Element 1: ";
cin >> NewElement;
for(int i=0; i < SetSize && NewElement != EmptyElement; i++)
{
if (contains(NewElement))
{
cout << "Element already in set.\n";
--i;
}
else
{
insert(NewElement);
}
if (i < SetSize-1)
{
cout << "Element " << (i+2) << ": ";
cin >> NewElement;
}
}
}
// Prints set elements on screen
template <class Type, int SetSize>
void set<Type,SetSize>::Print() const
{
cout << "Set elements: ";
for (int marker=0; marker<Cardinality; marker++)
cout << Element[marker] << ' ';
cout << endl;
cout << "Cardinality: " << Cardinality << endl;
}
Undigraf.cpp
#include "undigraf.h"
ostream& operator<<(ostream& OutStream, const undigraph::WeightEdge& OutWeightEdge)
{
OutStream << OutWeightEdge.start << "," << OutWeightEdge.finish << "," <<
OutWeightEdge.weight;
return OutStream;
}
istream& operator>>(istream& InStream, undigraph::WeightEdge& InWeightEdge)
{
InStream >> InWeightEdge.start >> InWeightEdge.finish >> InWeightEdge.weight;
return InStream;
}
undigraph::undigraph(int numvertex) : NumVertex(numvertex), Edge(new linklist<undigraph::WeightEdge>[numvertex]) {}
istream& operator>>(istream& InStream, undigraph& InGraph)
{
char line[80], *nextvertex, *nextweight;

undigraph::WeightEdge TempEdge;
cout << "Za svaki cvor, unesite parove (cvor, tezina) odvojene praznim mjestom.\n";
for (int source = 0; source < InGraph.NumVertex; source++)
{
cout << "Cvor " << source << ": ";
InStream.getline(line, sizeof(line));
if ((nextvertex = strtok(line, ",")) && (nextweight = strtok(0, " ")))
{
TempEdge.start = source;
TempEdge.finish = atoi(nextvertex);
TempEdge.weight = atoi(nextweight);
if (TempEdge.finish >= TempEdge.start)
InGraph.Edge[source].Insert(TempEdge);
while ((nextvertex = strtok(0, ",")) && (nextweight = strtok(0, " ")))
{
TempEdge.start = source;
TempEdge.finish = atoi(nextvertex);
TempEdge.weight = atoi(nextweight);
if (TempEdge.finish >= TempEdge.start)
InGraph.Edge[source].Insert(TempEdge);
}
}
}
return InStream;
}
ostream& operator<<(ostream& OutStream, const undigraph& OutGraph)
{
OutStream << "Lista cvorova i lukova.\n";
for (int source = 0; source < OutGraph.NumVertex; source++)
{
OutStream << "Cvor " << source << ": ";
ListIterator<undigraph::WeightEdge>Source(OutGraph.Edge[source]);
for (undigraph::WeightEdge Vertex = Source.Next();!Source.End(); Vertex = Source.Next() )
OutStream << Vertex << ' ';
OutStream << endl;
}
return OutStream;
}
Kruskal.cpp
#include "undigraf.h"
const int MAXGRAPHSIZE = 10;
void mincostgraph::MakeEdgeList()
{
for (int vertex = 0; vertex < NumVertex; vertex++)
{
ListIterator<undigraph::WeightEdge>temp(Edge[vertex]);
for (undigraph::WeightEdge Vertex = temp.Next();!temp.End();Vertex = temp.Next())
EdgeList.InsertSort(Vertex);
}
}
void mincostgraph::Kruskal()
{
mincostgraph spantree(NumVertex);
set<int,MAXGRAPHSIZE> connected[MAXGRAPHSIZE];
int EdgesAdded = 0;
int vertex1, vertex2;
int SetIndex1, SetIndex2;
bool cycle = false;
int vertex;
MakeEdgeList();
for (vertex = 0; vertex < NumVertex; vertex++)
connected[vertex].insert(vertex);
ListIterator<undigraph::WeightEdge> Edges(EdgeList);
for(undigraph::WeightEdge CurrEdge = Edges.Next();EdgesAdded < NumVertex-1 && !Edges.End();CurrEdge = Edges.Next())
{
vertex1 = CurrEdge.start;
vertex2 = CurrEdge.finish;
SetIndex1 = INT_MAX;
SetIndex2 = INT_MIN;
for (vertex = NumVertex - 1; vertex >= 0; vertex--)
{
if (connected[vertex].contains(vertex1))
SetIndex1 = vertex;
if (connected[vertex].contains(vertex2))
SetIndex2 = vertex;
cycle |= (SetIndex1 == SetIndex2);
}
if (!cycle)
{
spantree.Edge[CurrEdge.start].Insert(CurrEdge);
EdgesAdded++;
connected[SetIndex1 < SetIndex2 ? SetIndex1 : SetIndex2] = connected[SetIndex1] +
connected[SetIndex2];

}
cycle = false;
}
cout << "Minimalno spajajuce stablo:\n";
if (EdgesAdded < NumVertex - 1)
cout << "Warning: spanning tree incomplete.\n";
cout << spantree;
}
Main.cpp
#include "undigraf.h"
int main()
{
mincostgraph TestGraph(7);
cin >> TestGraph;
cout << TestGraph;
TestGraph.Kruskal();
return 0;
}
DIJAKSTRIN ALGORITAM
Sets.h
Settemp.h
Lists.h
Listtemp.h
Listiter.h
Itertemp.h
Undigraf.h
Undigraf.cpp // Isto kao kod Kruskalovog algoritma
Digrafw.h
#include "undigraf.h"
class digraphweight : public undigraph
{
public:
digraphweight(int numvertex = 10) :undigraph(numvertex) {}
friend istream& operator>>(istream& InStream,digraphweight& InGraph);
};
class minpathgraph : public digraphweight
{
protected:
int Weight(int vertex1, int vertex2);
public:
minpathgraph(int numvertex = 10) : digraphweight(numvertex) {}
void Dijkstra(int start);
};
Digrafw.cpp
#include "digrafw.h"
const int MAXGRAPHSIZE = 10;
istream& operator>>(istream& InStream, digraphweight& InGraph)
{
char line[80], *nextvertex, *nextweight;
undigraph::WeightEdge TempEdge;
cout << "Za svaki cvor, unesite parove (cvor, tezina).\n";
for (int source = 0; source < InGraph.NumVertex;source++)
{
cout << "Cvor " << source << ": ";
InStream.getline(line, sizeof(line));
if ((nextvertex = strtok(line, ",")) && (nextweight = strtok(0, " ")))
{
TempEdge.start = source;
TempEdge.finish = atoi(nextvertex);
TempEdge.weight = atoi(nextweight);
InGraph.Edge[source].Insert(TempEdge);
while ((nextvertex = strtok(0, ",")) && (nextweight = strtok(0, " ")))
{
TempEdge.start = source;
TempEdge.finish = atoi(nextvertex);
TempEdge.weight = atoi(nextweight);
InGraph.Edge[source].Insert(TempEdge);
}
}
}
return InStream;
}
int minpathgraph::Weight(int begin, int end)
{

ListIterator<undigraph::WeightEdge>temp(Edge[begin]);
for(undigraph::WeightEdge TempEdge = temp.Next();!temp.End(); TempEdge = temp.Next())
if (TempEdge.finish == end)
return TempEdge.weight;
return INT_MAX;
}
void minpathgraph::Dijkstra(int start)
{
set<int,MAXGRAPHSIZE> pathfound;
int mindistance[MAXGRAPHSIZE];
int tempmin,end,cost,vertex;
pathfound.insert(start);
mindistance[start] = 0;
for (vertex = 0; vertex < NumVertex; vertex++)
if (vertex != start)
mindistance[vertex] = Weight(start,vertex);
for (vertex = 0; vertex < NumVertex; vertex++)
{
int mindist = INT_MAX;
if (vertex != start)
{
for (end = 0; end < NumVertex; end++)
{
if (!pathfound.contains(end))
{
if (mindistance[end] < mindist)
{
tempmin = end;
mindist = mindistance[end];
}
}
}
if (mindist < INT_MAX)
{
pathfound.insert(tempmin);
for (end = 0; end < NumVertex; end++)
if (!pathfound.contains(end))
{
cost = Weight(tempmin,end);
if (cost < INT_MAX && mindist + cost < mindistance[end])
mindistance[end] = mindist + cost;
}
}
}
}
cout << "Minimalne udaljenosti od cvora " << start<< " do:\n";
for (vertex = 0; vertex < NumVertex; vertex++)
{
cout << "Cvor " << vertex << ": " ;
if(mindistance[vertex] == INT_MAX)
cout << "Ne postoji put.";
else
cout << mindistance[vertex];
cout << endl;
}
}
Dijkstra.cpp
#include "digrafw.h"
int main()
{
minpathgraph TestGraph(7);
int start;
cin >> TestGraph;
cout << TestGraph;
cout << "Unesite pocetni cvor: ";
cin >> start;
TestGraph.Dijkstra(start);
return 0;
}

You might also like