Bağli li̇steler (Linked List) – Yiğinlar (Stack) - Kuyruklar Konu Anlatımı Ömer Özselçuk
Bu sunumda Bağlı Listeler (linked list), Yığınlar (stack), kuyruk veri yapısı (QUEUES) konu anlatımı yapılmış. Örnek C kodları ve örnek algoritmalar ile anlatım desteklenmiştir.
Bağlı Liste (Linked List) Nedir?
Dizilerden sonra en çok kullanılan veri yapısıdır.
Doğrusal Liste (Linear List) yapısı yalnızca öncelik - sonralık ilişkisini yansıtabilecek yapıdadır.
Yığın Veri Yapısı Nedir ( Stack Data Type)
Nesne ekleme ve çıkarmalarının en üstten (top) yapıldığı veri yapısına stack (yığın) adı verilir.
QUEUES (KUYRUK) Veri Yapısı
Kuyruk veri yapısında da veri ekleme (enqueue) ve kuyruktan veri çıkarma (dequeue) şeklinde iki tane işlem tanımlıdır.
Yığınların tersine FIFO (First In First Out) prensibine göre çalışırlar ve ara elemanlara erişim doğrudan yapılamaz.
Tree is a non-linear data structure that can represent hierarchical relationships. It consists of nodes connected by edges. The root node has child nodes, and nodes may be leaf nodes or have child nodes themselves. Binary trees restrict nodes to having at most two children. General trees can be converted to binary trees by making the first child the left child and next siblings the right child. Binary trees can be built from input data by comparing values to determine left or right placement, or from traversal operations.
presentation on binary search trees for the subject analysis and design of algorithms, helpful to especially GTU students and computer and IT engineers
The document discusses various tree data structures and algorithms related to binary trees. It begins with an introduction to different types of binary trees such as strict binary trees, complete binary trees, and extended binary trees. It then covers tree traversal algorithms including preorder, inorder and postorder traversal. The document also discusses representations of binary trees using arrays and linked lists. Finally, it explains algorithms for operations on binary search trees such as searching, insertion, deletion and rebalancing through rotations in AVL trees.
AVL tree ( Balanced Binary Search Tree)-Data StructureYaksh Jethva
An AVL tree is another balanced binary search tree.
DEFINITION: An AVL Tree is a height-balanced binary search tree.
DEFINITION: The balance factor of a binary tree is the difference in heights of its two subtrees (hR - hL).
The balance factor (bf) of a height balanced binary tree may take on one of the values -1, 0, +1.
stack and queue array implementation in java.CIIT Atd.
This document discusses stack and queue data structures. It provides code examples in Java to demonstrate push and pop operations in a stack and enqueue and dequeue operations in a queue using arrays. Key aspects covered include LIFO and FIFO behavior, stack and queue operations, and sample code to implement stacks and queues in Java with output examples.
This document discusses hash tables, which are data structures that use a hash function to map keys to values in an array of buckets. Hash tables provide O(1) time performance for operations like insertion, search and deletion on average by distributing entries uniformly across the buckets. Collisions, where two keys hash to the same value, are resolved using techniques like separate chaining or open addressing. The document covers topics like choosing good hash functions, collision resolution methods, dynamic resizing, and applications of hash tables.
This document discusses linear search. It contains the names of group members working on the topic. It then defines linear search as checking all elements of an array or structure sequentially until the desired result is found. It provides an example of searching for a phone number in a telephone directory. The document includes pseudocode and C++ code implementations of linear search. It discusses using linear search on a linked list. It covers the advantages of linear search running in constant time if the item is first in the list, and the disadvantages of search time increasing linearly with the number of elements.
Different types of Shoring Algorithms with AnimationZakaria Hossain
This presentation discusses several sorting algorithms: bubble sort, insertion sort, selection sort, merge sort, and quick sort. Bubble sort, insertion sort, and selection sort have average and worst-case complexities of O(n^2), making them unsuitable for large data sets. Merge sort has a worst-case complexity of O(n log n), making it efficient. Quick sort also has average and worst-case complexities of O(n log n), making it suitable for large data sets. The presentation provides descriptions and animations of the sorting processes for each algorithm.
A 2-3 tree is a tree data structure where each internal node has either 2 or 3 children. It allows efficient search, insert, and delete operations by balancing the tree through splitting and merging nodes. To insert a new value, it is added to an leaf node. If the leaf contains 3 values, it is split by moving the middle value up to the parent. To delete a value, the target value is removed from its leaf node and neighboring nodes are merged if they become empty to maintain balance. This spreading of operations helps keep the 2-3 tree height balanced.
Linked List Static and Dynamic Memory AllocationProf Ansari
Static variables are declared and named while writing the program. (Space for them exists as long as the program, in which they are declared, is running.) Static variables cannot be created or destroyed during execution of the program in which they are declared.
Dynamic variables are created (and may be destroyed) during program execution since dynamic variables do not exist while the program is compiled, but only when it is run, they cannot be assigned names while it is being written. The only way to access dynamic variables is by using pointers. Once it is created, however, a dynamic variable does contain data and must have a type like any other variable. If a dynamic variable is created in a function, then it can continue to exist even after the function terminates.
Linked Linear List
We saw in previous chapters how static representation of linear ordered list through Array leads to wastage of memory and in some cases overflows. Now we don't want to assign memory to any linear list in advance instead we want to allocate memory to elements as they are inserted in list. This requires Dynamic Allocation of memory and it can be achieved by using malloc() or calloc() function.
But memory assigned to elements will not be contiguous, which is a requirement for linear ordered list, and was provided by array representation. How we could achieve this?
This document defines and describes trees and graphs as non-linear data structures. It explains that a tree is similar to a linked list but allows nodes to have multiple children rather than just one. The document defines key tree terms like height, ancestors, size, and different types of binary trees including strict, full, and complete. It provides properties of binary trees such as the number of nodes in full and complete binary trees based on height.
Shellsort is a sorting algorithm invented by Donald Shell in 1959 that was the first to break the quadratic time barrier of simpler sorting algorithms like insertion sort. It works by sorting elements with increasing proximity over multiple passes rather than just adjacent elements. The algorithm uses an increment sequence to determine the spacing between elements to compare and sort in each pass until the final pass sorts adjacent elements like an insertion sort. While faster than older quadratic algorithms, shellsort is still outperformed by more efficient algorithms like merge, heap, and quicksort for larger data sets.
Different Sorting tecniques in Data StructureTushar Gonawala
This document discusses various sorting algorithms like insertion sort, bubble sort, selection sort and quick sort. It provides pseudocode to implement insertion sort, bubble sort and selection sort. Insertion sort works by inserting elements in the sorted position of a list. Bubble sort works by exchanging adjacent elements to push larger elements to the end. Selection sort finds the minimum element and swaps it with the first unsorted element in each iteration. Quick sort is a highly efficient sorting algorithm that works by selecting a pivot element.
The document discusses B+ trees, which are self-balancing search trees used to store data in databases. It defines B+ trees, provides examples, and explains how to perform common operations like searching, insertion, and deletion on B+ trees in a way that maintains the tree's balanced structure. Key aspects are that B+ trees allow fast searching, maintain balance during operations, and improve performance over other tree structures for large databases.
non linear data structure -introduction of treeSiddhi Viradiya
The document defines trees and binary trees. A tree consists of nodes connected by branches, with one root node and zero or more subtrees. A binary tree restricts each node to have at most two children. The document discusses tree terminology like root, child, parent, leaf nodes. It also covers tree traversal methods like preorder, inorder and postorder. Finally, it shows how to construct a binary tree from its traversals.
This document provides information about different tree data structures including binary trees, binary search trees, AVL trees, red-black trees, splay trees, and B-trees. Binary search trees allow for fast searching and maintain an ordered structure. AVL and red-black trees are self-balancing binary search trees that ensure fast search, insert, and delete times by keeping the tree balanced. B-trees are multiway search trees that allow for efficient storage and retrieval of data in databases and file systems.
Bağli li̇steler (Linked List) – Yiğinlar (Stack) - Kuyruklar Konu Anlatımı Ömer Özselçuk
Bu sunumda Bağlı Listeler (linked list), Yığınlar (stack), kuyruk veri yapısı (QUEUES) konu anlatımı yapılmış. Örnek C kodları ve örnek algoritmalar ile anlatım desteklenmiştir.
Bağlı Liste (Linked List) Nedir?
Dizilerden sonra en çok kullanılan veri yapısıdır.
Doğrusal Liste (Linear List) yapısı yalnızca öncelik - sonralık ilişkisini yansıtabilecek yapıdadır.
Yığın Veri Yapısı Nedir ( Stack Data Type)
Nesne ekleme ve çıkarmalarının en üstten (top) yapıldığı veri yapısına stack (yığın) adı verilir.
QUEUES (KUYRUK) Veri Yapısı
Kuyruk veri yapısında da veri ekleme (enqueue) ve kuyruktan veri çıkarma (dequeue) şeklinde iki tane işlem tanımlıdır.
Yığınların tersine FIFO (First In First Out) prensibine göre çalışırlar ve ara elemanlara erişim doğrudan yapılamaz.
Tree is a non-linear data structure that can represent hierarchical relationships. It consists of nodes connected by edges. The root node has child nodes, and nodes may be leaf nodes or have child nodes themselves. Binary trees restrict nodes to having at most two children. General trees can be converted to binary trees by making the first child the left child and next siblings the right child. Binary trees can be built from input data by comparing values to determine left or right placement, or from traversal operations.
presentation on binary search trees for the subject analysis and design of algorithms, helpful to especially GTU students and computer and IT engineers
The document discusses various tree data structures and algorithms related to binary trees. It begins with an introduction to different types of binary trees such as strict binary trees, complete binary trees, and extended binary trees. It then covers tree traversal algorithms including preorder, inorder and postorder traversal. The document also discusses representations of binary trees using arrays and linked lists. Finally, it explains algorithms for operations on binary search trees such as searching, insertion, deletion and rebalancing through rotations in AVL trees.
AVL tree ( Balanced Binary Search Tree)-Data StructureYaksh Jethva
An AVL tree is another balanced binary search tree.
DEFINITION: An AVL Tree is a height-balanced binary search tree.
DEFINITION: The balance factor of a binary tree is the difference in heights of its two subtrees (hR - hL).
The balance factor (bf) of a height balanced binary tree may take on one of the values -1, 0, +1.
stack and queue array implementation in java.CIIT Atd.
This document discusses stack and queue data structures. It provides code examples in Java to demonstrate push and pop operations in a stack and enqueue and dequeue operations in a queue using arrays. Key aspects covered include LIFO and FIFO behavior, stack and queue operations, and sample code to implement stacks and queues in Java with output examples.
This document discusses hash tables, which are data structures that use a hash function to map keys to values in an array of buckets. Hash tables provide O(1) time performance for operations like insertion, search and deletion on average by distributing entries uniformly across the buckets. Collisions, where two keys hash to the same value, are resolved using techniques like separate chaining or open addressing. The document covers topics like choosing good hash functions, collision resolution methods, dynamic resizing, and applications of hash tables.
This document discusses linear search. It contains the names of group members working on the topic. It then defines linear search as checking all elements of an array or structure sequentially until the desired result is found. It provides an example of searching for a phone number in a telephone directory. The document includes pseudocode and C++ code implementations of linear search. It discusses using linear search on a linked list. It covers the advantages of linear search running in constant time if the item is first in the list, and the disadvantages of search time increasing linearly with the number of elements.
Different types of Shoring Algorithms with AnimationZakaria Hossain
This presentation discusses several sorting algorithms: bubble sort, insertion sort, selection sort, merge sort, and quick sort. Bubble sort, insertion sort, and selection sort have average and worst-case complexities of O(n^2), making them unsuitable for large data sets. Merge sort has a worst-case complexity of O(n log n), making it efficient. Quick sort also has average and worst-case complexities of O(n log n), making it suitable for large data sets. The presentation provides descriptions and animations of the sorting processes for each algorithm.
A 2-3 tree is a tree data structure where each internal node has either 2 or 3 children. It allows efficient search, insert, and delete operations by balancing the tree through splitting and merging nodes. To insert a new value, it is added to an leaf node. If the leaf contains 3 values, it is split by moving the middle value up to the parent. To delete a value, the target value is removed from its leaf node and neighboring nodes are merged if they become empty to maintain balance. This spreading of operations helps keep the 2-3 tree height balanced.
Linked List Static and Dynamic Memory AllocationProf Ansari
Static variables are declared and named while writing the program. (Space for them exists as long as the program, in which they are declared, is running.) Static variables cannot be created or destroyed during execution of the program in which they are declared.
Dynamic variables are created (and may be destroyed) during program execution since dynamic variables do not exist while the program is compiled, but only when it is run, they cannot be assigned names while it is being written. The only way to access dynamic variables is by using pointers. Once it is created, however, a dynamic variable does contain data and must have a type like any other variable. If a dynamic variable is created in a function, then it can continue to exist even after the function terminates.
Linked Linear List
We saw in previous chapters how static representation of linear ordered list through Array leads to wastage of memory and in some cases overflows. Now we don't want to assign memory to any linear list in advance instead we want to allocate memory to elements as they are inserted in list. This requires Dynamic Allocation of memory and it can be achieved by using malloc() or calloc() function.
But memory assigned to elements will not be contiguous, which is a requirement for linear ordered list, and was provided by array representation. How we could achieve this?
This document defines and describes trees and graphs as non-linear data structures. It explains that a tree is similar to a linked list but allows nodes to have multiple children rather than just one. The document defines key tree terms like height, ancestors, size, and different types of binary trees including strict, full, and complete. It provides properties of binary trees such as the number of nodes in full and complete binary trees based on height.
Shellsort is a sorting algorithm invented by Donald Shell in 1959 that was the first to break the quadratic time barrier of simpler sorting algorithms like insertion sort. It works by sorting elements with increasing proximity over multiple passes rather than just adjacent elements. The algorithm uses an increment sequence to determine the spacing between elements to compare and sort in each pass until the final pass sorts adjacent elements like an insertion sort. While faster than older quadratic algorithms, shellsort is still outperformed by more efficient algorithms like merge, heap, and quicksort for larger data sets.
Different Sorting tecniques in Data StructureTushar Gonawala
This document discusses various sorting algorithms like insertion sort, bubble sort, selection sort and quick sort. It provides pseudocode to implement insertion sort, bubble sort and selection sort. Insertion sort works by inserting elements in the sorted position of a list. Bubble sort works by exchanging adjacent elements to push larger elements to the end. Selection sort finds the minimum element and swaps it with the first unsorted element in each iteration. Quick sort is a highly efficient sorting algorithm that works by selecting a pivot element.
The document discusses B+ trees, which are self-balancing search trees used to store data in databases. It defines B+ trees, provides examples, and explains how to perform common operations like searching, insertion, and deletion on B+ trees in a way that maintains the tree's balanced structure. Key aspects are that B+ trees allow fast searching, maintain balance during operations, and improve performance over other tree structures for large databases.
non linear data structure -introduction of treeSiddhi Viradiya
The document defines trees and binary trees. A tree consists of nodes connected by branches, with one root node and zero or more subtrees. A binary tree restricts each node to have at most two children. The document discusses tree terminology like root, child, parent, leaf nodes. It also covers tree traversal methods like preorder, inorder and postorder. Finally, it shows how to construct a binary tree from its traversals.
This document provides information about different tree data structures including binary trees, binary search trees, AVL trees, red-black trees, splay trees, and B-trees. Binary search trees allow for fast searching and maintain an ordered structure. AVL and red-black trees are self-balancing binary search trees that ensure fast search, insert, and delete times by keeping the tree balanced. B-trees are multiway search trees that allow for efficient storage and retrieval of data in databases and file systems.
1. YZM 2116
Veri Yapıları
Yrd. Doç. Dr. Deniz KILINÇ
Celal Bayar Üniversitesi
Hasan Ferdi Turgutlu Teknoloji Fakültesi
Yazılım Mühendisliği
2. BÖLÜM - 6
Bu bölümde,
• Sıralama(Sort) Algoritmaları
1. Bubble Sort
2. Selection Sort
3. Insert Sort
4. Quick Sort
• Arama(Search) Algoritmaları
1. Linear Search
2. Binary Search
konusuna değinilecektir.
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
3. 3Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Sıralama, sayısal ortamdaki bilgilerin veya
verilerin belirli bir anahtar sözcüğe göre belirli
bir anlamda sıralı erişilmesini sağlayan bir
düzenlemedir.
• Örneğin: Telefon rehberindeki bir kişinin telefon
numarasının bulunması bir arama (search)
işlemidir.
• Genel olarak eleman toplulukları
o Daha etkin erişim amacıyla (aramak ve bilgi
getirmek) sıralanır ve/veya sıralı şekilde saklı
tutulurlar.
Sıralama Algoritmaları
4. 4Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Eleman (kayıt, yapı ...) toplulukları genelde (her
zaman değil) bir anahtara göre sıralı tutulurlar.
• Bu anahtar genelde elemanların bir alt alanı yani
üyesidir.
• Örneğin, Öğrenci
o Soyada göre sıralı olursa soyadı anahtardır,
o Numaraya göre sıralı olursa numara anahtardır,
o Nota göre sıralı olursa not alanı anahtardır.
Sıralama Algoritmaları (devam…)
• Elemanlar içindeki her elemanın anahtar değeri,
kendinden önceki elemanın anahtar değerinden
büyükse artan sırada (ascent – AZ), küçükse azalan
(descent – ZA) sırada sıralıdır.
5. Sıralama Algoritmaları (devam…)
• Sıralama algoritmalarının hesaplama verimliliği
açısından; VY olarak array, stack, queue veya tree
kullanılabilir.
• Literatürde çok farklı sıralama algoritmaları mevcuttur:
– Bubble Sort
– Selection Sort
– Insertion Sort
– Quick Sort
– Heap Sort
– Merge Sort
– Shell Sort
– …
5Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
6. 1. Bubble (Kabarcık) Sort
6Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Verimliliği düşük ancak mantığı basit bir
sıralama algoritmasıdır.
• “n” boyutlu bir a[] dizisi için artan sıralamayı
düşünelim.
• Bubble Sort (BS) en fazla (n-1) taramada
(pass) sıralamayı tamamlar.
7. • İlk taramada a0 ve a1 kıyaslanır eğer a0 > a1 ise iki
değer takas (swap) edilir.
• Değilse bu defa a1 ve a2 kıyaslanarak gerekirse yer
değişikliği yapılır.
• Bu işlem her seferinde takas edilme durumu
oluşmayana kadar sürer.
• Sadece 1. taramada tüm dizi elemanları
dolaşılmaktadır.
• Her taramada
– (dizinin eleman sayısı) – (tarama sayısı) kadar eleman
dolaşılır.
7
1. Bubble (Kabarcık) Sort (devam…)
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
8. 8
• [5, 1, 12, -5, 16] dizisinde Bubble Sort işletimi
gösterilmiştir.
1. Bubble (Kabarcık) Sort (devam…)
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
9. 9
• Aşağıdaki animasyonda [25, 17, 31, 13, 2]
dizisinin Bubble Sort algoritmasının işletilmesi
sonucu oluşan sıralamalar gösterilmiştir.
1. Bubble (Kabarcık) Sort (devam…)
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
10. public void Sort(int[] items)
{
int tarama;
bool swapped = false;
for (tarama = 0; tarama < items.Length; tarama++)
{
swapped = false;
//Her tarama sonrası sondaki elemanları zaten sıralı olacağından
onları karşılaştırmamak için tarama sayısı çıkart
for (int i = 0; i < (items.Length - tarama - 1); i++)
{
if (items[i] > items[i + 1])
{
int temp;
temp = items[i];
items[i] = items[i + 1];
items[i + 1] = temp;
swapped = true;
}
}
//Eğer geçişte sıralama yapılmadıysa, bir sonraki geçişe geçme, işlemi bitir.
if (!swapped)
break;
}
} 10
1. Bubble (Kabarcık) Sort Implementasyon
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
11. • Quadratic işlem karmaşıklığı sahip olan Bubble
Sort algoritması, büyük n değerlerinde en yavaş
performansa sahip olan sıralama algoritmasıdır.
• Elemanların ilk dizilimi sıralama performansını
önemli ölçüde etkiler.
• Örneğin Neredeyse sıralanmış bir dizide,
– Baştaki Büyük değerli elemanların dizinin sonuna
ilerlemesi hızlı iken
– Sondaki Küçük değerli elemanların dizinin başına
getirilmesi yavaştır
11
1. Bubble (Kabarcık) Sort (devam…)
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
12. 12
1. Bubble (Kabarcık) Sort (devam…)
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Bu sorunu çözmek için “coctail sort” algoritması
geliştirilmiştir.
13. • İç döngü: (n - 1) + (n - 2) + … + 1 = (n -1 + 1)/2
• Dış döngü: n
• Toplam İterasyon: n * (n / 2) = n2 / 2
• Big O Karmaşıklığı: O(n2)
13
1. Bubble Sort Karmaşıklığı
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
14. • Bubble Sort algoritması gibi verimliliği düşük
ancak mantığı yine basit bir sıralama
algoritmasıdır.
• Takas sayısı çok daha az olduğu için Bubble
Sort algoritmasının iyileştirilmiş hali gibi
düşünülebilir.
14Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
2. Selection Sort
15. 15
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
Algoritmanın temel çalışma mantığı aşağıdaki gibidir:
• Dizinin ilk elemanından başla.
• Dizideki en küçük elemanı bul, A[0] indisindeki
elemanla karşılıklı takas yap (swap).
• İkinci en küçük elemanı A[1] ile A[n] arasında ara,
• İkinci en küçük elemanı bul,
– Bu eleman ile A[1]’i takas yap.
• Takas işlemine dizi bitene kadar devam et.
• Her adımda
– Sol tarafta sıralı bir alt dizi,
– Sağ tarafta ise sırasız bir alt dizi elde edilir.
2. Selection Sort (devam…)
16. 16Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Aşağıda [7, 4, 5, 9, 8, 2, 1] dizisinde Selection Sort
algoritmasının işletilme adımları gösterilmiştir.
2. Selection Sort (devam…)
17. 17Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Aşağıdaki animasyonda [25, 17, 31, 13, 2] dizisinin
Selection Sort algoritmasının işletilmesi sonucu oluşan
sıralamalar gösterilmiştir.
2. Selection Sort (devam…)
DİKKAT
• Animasyondaki gibi her
iterasyonda swap etmek
gereksizdir.
• Kalanlar arasında en
küçük bulunduğunda
swap edilmesi yeterlidir.
18. 18Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
public void Sort(int[] items)
{
int n = items.Length;
int minIndis = 0;
for (int i = 0; i < n; i++)
{
//minimumum i olarak ayarla
minIndis = i;
//i'den sonraki tüm elemanları tara
for (int j = i + 1; j < n; j++)
{
//daha küçük eleman bulursan indisini sakla
if (items[j] < items[minIndis])
minIndis = j;
}
//en küçük indis değiştiyse, yani i'den sonraki elemanlardan
birisi i'den küçükse
//takas işlemi gerçekleştir
if (minIndis != i)
{
int temp = items[i];
items[i] = items[minIndis];
items[minIndis] = temp;
}
}
}
2. Selection Sort Implementasyon
19. 19
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Algoritma ilk geçiş için (n - 1) karşılaştırma, ikinci
geçiş için ise (n - 2) karşılaştırma yapar.
• A(n) elemanlı dizi için toplam karşılaştırma adedi ve
karmaşıklık
• A(n) = (n – 1) + (n – 2) + ... + 2 + 1 veya
• (n * n ) / 2 = 1 / 2 (n2)
• veya O(n2) olur.
2. Selection Sort Karmaşıklığı
20. 20Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
Örneğin, masada bir deste oyun kâğıdı, sırasız ve sırtları
yukarıya doğru duruyor olsun.
• Desteden en üstteki kartı alalım. Onu masaya yüzü görünür
biçimde koyalım. Tek kart olduğu için sıralı bir kümedir.
• Sırasız destenin üstünden bir kart daha çekelim. Masadaki ilk
çektiğimiz kart ile karşılaştıralım.
• Gerekirse yerlerini değiştirerek, çektiğimiz iki kartı küçükten
büyüğe doğru sıralayalım.
• Sırasız destenin üstünden bir kart daha çekelim. Masaya sıralı
dizilen iki kart ile karşılaştıralım. Gerekirse yerlerini
değiştirerek çekilen üç kartı küçükten büyüğe doğru
sıralayalım.
• Bu işleme sırasız deste bitene kadar devam edelim. Sonunda,
oyun kâğıtlarını sıralamış oluruz.
3. Insertion Sort
21. 21Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Örnek: A[n]= [65, 50, 30, 35, 25, 45] dizisini Insertion Sort
kullanarak sıralayalım.:
Pass 0 İlk adımda sıralanmış dizide hiç eleman yokken tüm elemanlar sıralanmamış dizide
yer alır.
Pass 1
Sıralamaya başlarken A[0] (ya da 65) sıralanmış dizinin ilk elemanı kabul edilir ve
sıralanmamış dizinin ilk elemanı ile A[1] (ya da 50) karşılaştırılır. 50, 65’ten küçük
olduğu için sıralı dizide 65 bir sağa kayarken 50 ilk sıraya yerleşir.
Pass 2 İşlem A[2] (30) için tekrarlanır. 30 sıralı dizide önce 65’ile kıyaslanır ve 65 bir sağa
kayar. 30 bu defa 50 ile kıyaslanır ve 50 bir sağa kayar.
Pass 3 İşlem A[3] (35) için tekrarlanır. 35 sıralı dizide önce 65’ile kıyaslanır ve 65 bir sağa
kayar. 35 bu defa 50 ile kıyaslanır ve 50 bir sağa kayar. 35, son olarak 30 ile
karşılaştırılır, 30’dan büyük olduğu için yer değiştirme olmaz ve 35 A[1]’e insert edilir.
Pass 4 İşlem A[4] (25) için tekrarlanır. 25 sıralı dizide önce 65’ile kıyaslanır ve 65 bir sağa
kayar. 25 bu defa 50 ile kıyaslanır ve 50 bir sağa kayar. 25 daha sonra 35 ile kıyaslanır
ve 35 bir sağa kayar. 25, son olarak 30 ile karşılaştırılır, 30’dan küçük olduğu için yer
değiştirme olur 30 sağa kayar ve 25 A[0]’a insert edilir.
Pass 5 İşlem A[5] (45) için tekrarlanır. 45 sıralı dizide önce 65’ile kıyaslanır ve 65 bir sağa
kayar. 45 bu defa 50 ile kıyaslanır ve 50 bir sağa kayar. 45 son olarak 35 ile
karşılaştırılır, 35’den büyük olduğu için yer değiştirme olmaz ve 45 A[3]’e insert edilir.
3. Insertion Sort (devam…)
23. 23Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
3. Insertion Sort Implementasyonu
public override void Sort(int[] items)
{
int i, j, moved;
for (i = 1; i < items.Length; i++)
{
moved = items[i];
j = i;
while (j > 0 && items[j - 1] > moved)
{
items[j] = items[j - 1];
j--;
}
items[j] = moved;
}
}
24. 24Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• A(n) elemanlı dizi için toplam karşılaştırma
adedi ve karmaşıklık
• A(n) = (n – 1) + (n – 2) + ... + 3 + 2 + 1 veya
• (n * ( n + 1 ) / 2) = 1 / 2 (n2+n)
• veya
• O(n2) olur.
3. Insertion Sort Karmaşıklığı
25. 25Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Quick Sort (QS) algoritması “böl-fethet” mantığına
uygun olarak sıralama yapan recursive
(özyinelemeli) bir algoritmadır.
• Ticari sıralama algoritmalarında QS sıklıkla
kullanılır.
• QS algoritması temel olarak diziyi bir pivot
(mihenk) etrafında iki alt-diziye bölerek:
o Pivota küçük eşit elemanları pivotun sol tarafına
o Pivottan büyük elemanları pivotun sağ tarafına
yerleştirir.
4. Quick Sort
26. 26Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Aynı işlem, her alt dizi için bir pivot seçerek
tekrarlar ve bu işlem tek eleman kalana kadar devam
eder.
• QS için farklı pivot seçim yöntemleri bulunmaktadır.
• Pivot olarak dizinin
o İlk elemanı,
o Son elemanı,
o Orta elemanı,
o Rastgele bir dizi elemanı,
• seçilerek sıralama işlemi gerçekleştirilebilmektedir.
4. Quick Sort (devam…)
27. 27Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• A[i] = {2, 17, -4, 42, 9, 26, 11, 3, 5, 28} dizisi verilsin.
• Dizinin terimleri arasından birisini mihenk (pivot) olarak
seçelim. Yapacağımız işlemde eş uygulamayı sağlamak
için mihengi şöyle seçelim: Ayrıştırılacak (alt) dizinin ilk
teriminin indisi ile son teriminin indislerini toplayıp 2 ye
bölelim. Bölümün tamsayı parçasını mihengin indisi
olarak seçelim.
• (0 + 9) / 2 = 4 (pivot, tam kısım)
4. Quick Sort Örnek (devam…)
28. 28Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Şimdi (A[4]=9) mihenginin solunda
o 9’dan büyük olan terimler varsa onları sağ
tarafa taşıyacağız.
o Benzer şekilde, 9’un sağında 9’dan küçük
terimler varsa, onları sol tarafa taşıyacağız.
o Özel olarak mihenge eşit olan başka terimler varsa,
onları sağa ya da sola taşıyabiliriz.
4. Quick Sort Örnek (devam…)
29. 29Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Pratik yöntem: Sol elimizle sol kısmı sağ elimizle
de sağ kısmı tarayacağız.
• Solda mihenkten büyük ilk eleman:
• A[1] = 17 solda tut
• Sağda mihenkten küçük ilk eleman:
• A[8] = 5 sağda tut
• İki elemanı yer değiştir.
4. Quick Sort Örnek (devam…)
30. 30Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Aynı işlemi solda 9’dan büyük, sağda 9’dan küçük
olan sayılar çifti için tekrarlayacağız.
• Görüldüğü gibi, 42 ve 3 sayıları takas edilecektir.
4. Quick Sort Örnek (devam…)
31. 31Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Bu eylem sonunda, diziyi {2, 5, -4, 3}, {9} ve {26, 11,
42, 17, 28} olmak üzere üç altdiziye ayırmış oluruz.
• Soldaki alt dizideki her terim, sağdaki alt dizideki her
teriminden küçüktür.
• Şimdi soldaki ve sağdaki altdizileri yeni dizilermiş
gibi düşünüp, aynı yöntemle onları ayrıştırabiliriz.
• Sonra onların da sol ve sağ alt dizilerini ayrıştırabiliriz.
Bu süreç, alt diziler tek terimli birer diziye
indirgenene kadar devam edecektir.
4. Quick Sort Örnek (devam…)
34. 34Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Eğer şanslı isek,
seçilen her eleman
ortanca değere
yakınsa
(Average Case)
o O(nlogn)
karmaşıklığa
sahipken
4. Quick Sort Karmaşıklığı
35. 35Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• En kötü durumda
ise parçalama
dengesiz olacak ve
n iterasyonla
sonuçlanacaktır
(Worst Case)
o O(n2)
4. Quick Sort Karmaşıklığı
37. 37Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Arama, bir bilgi kümesi içerisinde belirli bir anahtar
sözcüğe dayanılarak onunla ilgili diğer bilgilere
erişme/elde etme işlemidir.
• Bilgisayar ve benzeri sayısal ortamlarda tutulan
bilgilerin anlamlı olarak kullanılması ve onlar
üzerinde işlemler yapılması için her şeyden önce
bilginin olup olmadığı ve varsa belleğin neresinde
olduğunun belirlenmesi gerekir.
• Bu işlem, bir arama algoritması ile gerçekleştirilir.
Arama Algoritmaları
38. 38Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Arama işleminin yapılış şekli bilgiye ait verilerin
düzenlenme şekline (sıralı / sırasız olması) ve
bellekte tutulmasına göre farklılıklar gösterir.
• İki tür arama işlemi gerçekleştirilebilmektedir:
1. Dahili (internal) arama
2. Harici (external) arama
Arama Algoritmaları (devam…)
39. 39Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
1. Dahili (internal) arama: Arama işlemi bellek
üzerinde tutulan veriler üzerinde yapılır. Veriye erişim
hızlı olduğu için verilerin yer değiştirmesi, araya
ekleme, aradan çıkarma gibi işlemler daha hızlı
gerçekleşir.
2. Harici (external) arama: Arama işlemi disk,
yedekleme birimi gibi belleğe göre daha yavaş olan
saklama birimleri üzerinde yapılır. Dolayısı ile
verilerin yer değiştirmesi, bir veriden diğerine
atlanması, arkada kalanların öne doğru kaydırılarak bir
verinin silinmesi veya arkaya doğru kaydırılarak yeni
bir veriye yer açılması gibi işlemler zaman alır.
Arama Algoritmaları (devam…)
40. 40Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Bu bölümde üzerinde duracağımız arama
algoritmaları aşağıdaki gibidir:
1. Linear Search (Doğrusal Arama)
2. Binary Search (İkili Arama)
Arama Algoritmaları (devam…)
41. 41Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• Herhangi bir liste veya dizi içerisindeki ilk
elemandan başlanarak son elemana kadar, dizi
terimleri ile aranan sözcük karşılaştırılır, sözcük
bulunduğunda geriye dizi teriminin indisi,
bulunamadığında ise -1 (false) değeri döndürülür.
Not: Dizi sırasız ve az elemana sahipse tercih edilen
bir algoritmadır.
1. Linear Search (Doğrusal Arama)
42. 42Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
public override int Search(int[] items, int searchKey)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i] == searchKey)
return i;
}
return -1;
}
Linear Search Big O Karmaşıklığı: O(n)
1. Linear Search (Doğrusal Arama) (devam…)
43. 43Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• İkili arama sıralı veriler üzerinde çalışan bir
algoritmadır.
• Verilerin önceden belirli bir anahtar sözcüğe göre
sıralanması gerekmektedir.
• Örneğin, veriler bir dizi üzerinde ardışık olarak sıralı
şekilde tutuluyorsa ikili arama yapılabilir.
• Sıralı veriler her adımda iki parçaya bölünerek
arama işlemi gerçekleştirilir.
• İkili arama algoritması, tasarım olarak parçala fethet
(divide and conquere) türündedir.
2. Binary Search (İkili Arama)
44. 44Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
• İkili arama algoritmasının sözde kodu aşağıdaki
gibidir:
o Aranacak uzayın tam orta noktasına bak
o Eğer aranan değer bulunduysa bitir
o Eğer bakılan değer aranan değerden büyükse
Arama işlemini problem uzayının küçük
elamanlarında devam ettir.
o Eğer bakılan değer aranan değerden küçükse
Arama işlemini problem uzayının büyük
elemanlarında devam ettir.
o Şayet bakılan aralık 1 veya daha küçükse
aranan değer bulunamadı olarak bitir.
2. Binary Search (İkili Arama) (devam…)
51. Yararlanılan Kaynaklar
• Ders Kitabı:
• Data Structures through JAVA, V.V.Muniswamy
• Yardımcı Okumalar:
• Data Structures and Algorithms in Java, Narashima
Karumanchi
• Data Structures, Algorithms and Applications in Java,
Sartaj Sahni
• Algorithms, Robert Sedgewick
Celal Bayar Üniversitesi – YZM 2116 Veri Yapıları
Editor's Notes
Aşağıda literatürde çok sık karşılaşılan ve bir kısmı bu bölümde incelenen algoritmaların ortalama ve en kötü performansları verilmiştir. Quick Sort algoritması Merge ve Heap sort algoritmalarına göre, en kötü durumda daha yavaş görünse de, pratikte onlarla aynı performansa sahiptir, bu nedenle daha çok tercih edilmektedir.
Aşağıdaki örnekte, 12 elemanlı küçükten büyüğe sıralanmış A dizisi üzerinde, 22 elemanı İkili Arama algoritması ile aranmaktadır.
Loop’un k kadar döndüğünü varsayarsak;
k adımında 2i = n olur.
Her iki tarafın logaritmasını alırsak; ilog2 = logn ve i = log n olur.
i’ye bağlı olarak (problemi ikiye bölen değişken!)
Loop’un k kadar döndüğünü varsayarsak;
k adımında 2i = n olur.
Her iki tarafın logaritmasını alırsak; ilog2 = logn ve i = log n olur.
i’ye bağlı olarak (problemi ikiye bölen değişken!)
Loop’un k kadar döndüğünü varsayarsak;
k adımında 2i = n olur.
Her iki tarafın logaritmasını alırsak; ilog2 = logn ve i = log n olur.
i’ye bağlı olarak (problemi ikiye bölen değişken!)
Loop’un k kadar döndüğünü varsayarsak;
k adımında 2i = n olur.
Her iki tarafın logaritmasını alırsak; ilog2 = logn ve i = log n olur.
i’ye bağlı olarak (problemi ikiye bölen değişken!)