SlideShare a Scribd company logo
Data Structures & Algorithm
Sorting I
Session VI
Dr. V.Umadevi M.Sc(CS &IT). M.Tech (IT)., M.Phil., PhD.,
D.Litt.,
Director, Department of Computer Science, Jairams Arts
and Science College, Karur.
Data Structures & Algorithm
Sorting I
• Introduction to Sorting
• Exchange Sort
– Bubble sort
– Quick Sorts
• Selection and Tree Sorting
– Straight Selection Sort
– Heap Sort
Data Structures & Algorithm
Sorting
General Def : Arrange the data in some appropriate order according to some
key.
Examples:
• An English dictionary, in which all words are arranged in alphabetic
order.
• A phone directory, in which phone numbers are listed in some order.
• Sorting is the fundamental algorithmic problem in computer science.
• Learning the different sorting algorithms is like learning scales for a
musician.
• Formal Def : Given a sequence of numbers <x1, x2, ..., xn>, a sorting
algorithm must compute a permutation <x'1, x'2, ..., x'n> such that x'1 ≤
x'2≤ ... ≤ x'n
Data Structures & AlgorithmExchange Sorts
Bubble Sort
• This sort is oldest and simplest sort in use.
• Its is the slowest sort.
• Works by comparing each item in the list with the item next to it, swapping
them if required.
• Algorithm repeat this process until it makes a pass all the way through the
list without swapping any items.
• Causes larger values to “Sink" to the end of the list while smaller values “bubble"
towards the beginning of the list.
• Bubble sort is generally considered to be the most inefficient sorting algorithm in
common usage.
• Under best-case conditions (the list is already sorted), the bubble sort can
approach a constant O(n) level of complexity.
Pros: Simplicity and ease of implementation.
Cons: Horribly inefficient.
Data Structures & Algorithm
void bubbleSort(int numbers[], int array_size)
{
int i, j, temp;
for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
}
Source code for Bubble sort
Data Structures & AlgorithmExample:
1 2 3 4 5 6 7 // Positions
-------------
4 6 2 5 7 3 4 // Initial sequence
4 2 5 6 3 4 7 // Swapped: 2-3, 3-4, 5-6, 6-7; last_swap=6
2 4 5 3 4 6 7 // Swapped: 1-2, 4-5, 5-6; last_swap=5
2 4 3 4 5 6 7 // Swapped: 3-4, 4-5; last_swap=4
2 3 4 4 5 6 7 // Swapped: 2-3; last_swap=2
2 3 4 4 5 6 7 // No swapping; last_swap=0; end
• Analysis: Best case performing one pass which require n-1 comparisons
• Consequently best case is O(n).
• Worst case performance of bubble sort is n(n-1)/ 2 comparison and exchange
• Average case is analysis is O(n2
).
• Average number of comparison and exchanges are both O(n2
).
Bubble Sort Analysis
Data Structures & AlgorithmQuick Sort
• Invented in 1960 by C. A. R. Hoare
• Popular and well investigated
• Easy to be implemented and improved
• Quick sort is an in-place, divide-and-conquer, massively recursive sort.
• Recursive algorithm consists of four steps:
1. If there are one or less elements in the array to be sorted, return
immediately.
2. Pick an element in the array to serve as a "pivot" point. (Usually the left-
most element in the array is used.)
3. Split the array into two parts - one with elements larger than the pivot
and the other with elements smaller than the pivot.
4. Recursively repeat the algorithm for both halves of the original array.
Data Structures & Algorithm
Initial Step - First Partition Sort Left Partition in the same way
• Partition array into two segments.
• First segment all elements are less than or equal to the pivot value.
• Second segment all elements are greater or equal to the pivot value.
• Sort the two segments recursively.
• Pivot can only be found by scanning the whole array and this would slow down
the algorithm.
• Quick sort is fastest on average, but sometimes unbalanced partitions can lead
to very slow sorting.
• The best sorting algorithm when there is no infinite memory space.
Data Structures & Algorithm
Quicksort Example
Analysis
• Worst-Case Analysis - the pivot is the smallest element, all the time (requires N
recursive call of quicksort O(N)with comparison for a level). So the
algorithm O(N2
)will be run in a time.
• Best-Case Analysis - the pivot is in the middle, all the time. The running time
is . O(N Log N)
• Average-Case Analysis - each of the sizes for array (s1) is equally likely. The
running time for this case is also O(N Log N) .
Pros: Extremely fast.
Cons: Very complex algorithm, massively recursive.
Data Structures & Algorithmvoid quickSort(int numbers[], int array_size)
{ q_sort(numbers, 0, array_size - 1); }
void q_sort(int numbers[], int left, int right)
{
int pivot, l_hold, r_hold;
l_hold = left;
r_hold = right;
pivot = numbers[left];
while (left < right)
{
while ((numbers[right] >= pivot) && (left < right))
right--;
if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left < right))
left++;
if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
q_sort(numbers, left, pivot-1);
if (right > pivot)
q_sort(numbers, pivot+1, right);
}
Code For Quick Sort
Data Structures & Algorithm
Analysis of Exchange Sorts
Exchange Sorts Running Time
Algorithms Best Case Average
Case
Worst
Case
Bubble Sort O(n2
) O(n2
) O(n2
)
Quick Sort O(n Log n) O(n Log n) O(n2
)
Data Structures & AlgorithmStraight Selection Sort
• Selection sort is one in which successive elements are selected in order
and placed into their proper sorted positions.
• Elements of the input may have to be preprocessed to make the ordered
selection possible.
• Def: An algorithm which orders items by repeatedly looking through
remaining items to find the least one and moving it to a final location.
• Select successive elements in ascending order and place them into their
proper position.
– Find the smallest element from the array, and exchange it with the first
element.
– Find the second smallest element, and exchange it with the second
element.
– Repeat until sorted in proper order.
– Searching the smallest key in the record is called pass
Data Structures & Algorithm
• 42 23 74 11 65 58 94 36 99 87 //Input
• [11 ] 23 74 42 65 58 94 36 99 87
• [11 23 ] 74 42 65 58 94 36 99 87
• [11 23 36 ] 42 65 58 94 74 99 87
• [11 23 36 42 ] 65 58 94 74 99 87
• [11 23 36 42 58 ] 65 94 74 99 87
• [11 23 36 42 58 65 ] 94 74 99 87
• [11 23 36 42 58 65 74 ] 94 99 87
• [11 23 36 42 58 65 74 87 ] 99 94
• [11 23 36 42 58 65 74 87 94 ] 99
• 11 23 36 42 58 65 74 87 94 99 //Output
• Selection sort works by selecting the smallest unsorted item remaining in
the list, and then swapping it with the item in the next position to be
filled.
Example of Selection Sort
Data Structures & Algorithm
•Starting near the top of the array extract the 3.
•Then the above elements are shifted down until we find the correct place to
insert the 3.
•This process repeats in Figure(b) with the next number.
• Finally, in Figure(c) complete the sort by inserting 2 in the correct place.
Data Structures & Algorithm
• N-1 pass is required in order to perform the sort.
• During the Ist pass in which the record with the smallest key is found n-1
records are compared.
• In general for ith
pass of the sort n-I comparisons are required.
• Total number of comparisons is
• Σn-1
n-I =n(n-1)/2
• i=1
• Therefore the number of comparison is proportional to n2
i.e O(n2
)
• Selection sort has a complexity of O(n2).
Pros: Simple and easy to implement.
Cons: Inefficient for large lists, so similar to the more efficient
insertion sort that the insertion sort should be used in its
place.
Analysis of Selection Sort
Data Structures & Algorithm
selection( int a[], int N) /* in C */ /* sort a[1..N], NB. 1 to N */
{ int i, j, smallest, aSmallest, temp;
for (i=1; i < N; i++)
{ /* invariant: a[1..i-1] sorted and elements a[1..i-1] <= a[i..N] */
smallest = i; /* find smallest in a[i..N] */
aSmallest = a[i];
for(j=i+1; j <= N; j++) /* a[smallest] is the least element in a[i..j-1] */
if ( a[j] < aSmallest )
{
smallest=j;
aSmallest=a[j];
} /* a[smallest] is the least element in a[i..j] */
temp=a[i];
a[i]=a[smallest];
a[smallest]=temp;
/*swap*/ /* a[1..i] sorted and elements a[1..i] <= a[i+1..N] */
} /* a[1..N-1] sorted and elements a[1..N-1] <= a[N] */
/* i.e. a[1..N] sorted. */
Source Code for Selection Sort
Data Structures & Algorithm
Heap Sort
• Elegant and efficient, widely used.
• No extra memory is needed.
• Heap sort is based on a tree structure that reflects the packing order in a
corporate hierarchy.
• This method has two phases.
• First the tree representing file is converted to heap
• Second stage output sequence is generated in decreasing order
• A heap is complete binary tree in which each node satisfies the heap condition
represented as an array.
Def- a heap is a list in which each entry contains a key and for all positions k in the
list, the key at position k is at least as large as the keys in positions
2k and 2k+1 provided these positions exist in the list.
• A complete binary tree is said to satisfy the heap condition if the key of each node
is greater than or equal to the key in its children, thus the root node
will have the largest key value.
Data Structures & Algorithm
Analysis of Heap sort
• Elegant and efficient, widely used.
• No extra memory is needed.
• On average, Heap sort is third place in speed.
• But inner loop is a bit longer than that of Quick Sort, about twice as slow
as Quick Sort on the average.
• Building of the heap uses at most 2N comparisons,
• In the worst case, at most 2n log n - O(n) comparisons are used by
heapsort.
• Good performance (NlogN) is guaranteed.
Data Structures & Algorithm
Example of Heap Sort
Data Structures & Algorithm
Data Structures & Algorithm
void heapSort(int numbers[], int array_size)
{ int i, temp;
for (i = (array_size / 2)-1; i >= 0; i--)
siftDown(numbers, i, array_size);
for (i = array_size-1; i >= 1; i--)
{ temp = numbers[0]; numbers[0] = numbers[i]; numbers[i] = temp;
siftDown(numbers, 0, i-1);
}
}
void siftDown(int numbers[], int root, int bottom)
{ int done, maxChild, temp; done = 0;
while ((root*2 <= bottom) && (!done))
{ if (root*2 == bottom) maxChild = root * 2;
else if (numbers[root * 2] > numbers[root * 2 + 1])
maxChild = root * 2;
else maxChild = root * 2 + 1;
if (numbers[root] < numbers[maxChild])
{ temp = numbers[root];
numbers[root] = numbers[maxChild];
numbers[maxChild] = temp;
root = maxChild;
}
else done = 1;
}
}

More Related Content

What's hot (20)

PDF
Introduction to Data Structure
Prof Ansari
 
PDF
Data Structures & Algorithm design using C
Emertxe Information Technologies Pvt Ltd
 
PPT
Chapter 5 ds
Hanif Durad
 
PPT
Chapter 2.2 data structures
sshhzap
 
PPT
Introduction to data structure by anil dutt
Anil Dutt
 
PDF
Data structures (introduction)
Arvind Devaraj
 
PPT
Data structures
Manaswi Sharma
 
PDF
Data Structures (BE)
PRABHAHARAN429
 
PDF
Elementary data structure
Biswajit Mandal
 
PPT
Data structure lecture 1
Kumar
 
PDF
Data structure ppt
Prof. Dr. K. Adisesha
 
PPTX
Lecture 1 and 2
SaheedTundeZubairSTA
 
PPTX
Data structure and algorithm All in One
jehan1987
 
PPTX
Data structures and algorithms
Julie Iskander
 
PDF
Introduction to data structure
Zaid Shabbir
 
PDF
Data Structure and its Fundamentals
Hitesh Mohapatra
 
PDF
Data structures Basics
DurgaDeviCbit
 
PPTX
Presentation on Elementary data structures
Kuber Chandra
 
PPTX
Data Structure
Karthikeyan A K
 
PPTX
Introduction to data_structure
Ashim Lamichhane
 
Introduction to Data Structure
Prof Ansari
 
Data Structures & Algorithm design using C
Emertxe Information Technologies Pvt Ltd
 
Chapter 5 ds
Hanif Durad
 
Chapter 2.2 data structures
sshhzap
 
Introduction to data structure by anil dutt
Anil Dutt
 
Data structures (introduction)
Arvind Devaraj
 
Data structures
Manaswi Sharma
 
Data Structures (BE)
PRABHAHARAN429
 
Elementary data structure
Biswajit Mandal
 
Data structure lecture 1
Kumar
 
Data structure ppt
Prof. Dr. K. Adisesha
 
Lecture 1 and 2
SaheedTundeZubairSTA
 
Data structure and algorithm All in One
jehan1987
 
Data structures and algorithms
Julie Iskander
 
Introduction to data structure
Zaid Shabbir
 
Data Structure and its Fundamentals
Hitesh Mohapatra
 
Data structures Basics
DurgaDeviCbit
 
Presentation on Elementary data structures
Kuber Chandra
 
Data Structure
Karthikeyan A K
 
Introduction to data_structure
Ashim Lamichhane
 

Similar to Data Structures 6 (20)

DOCX
Sorting
BHARATH KUMAR
 
PDF
Class13_Quicksort_Algorithm.pdf
AkashSingh625550
 
PPTX
Algorithms and Data Structures - Parahyangan Catholic University Credit Lionov
Pratik Parmar
 
PPT
03_sorting and it's types with example .ppt
vanshii9976
 
PPT
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
PPT
quicksortnmsd cmz ,z m,zmm,mbfjjjjhjhfjsg
RafishaikIT02044
 
PPTX
sorting-160810203705.pptx
VarchasvaTiwari2
 
PPTX
SORT AND SEARCH ARRAY WITH WITH C++.pptx
narifmsit18seecs
 
PPTX
my docoment
NeeshanYonzan
 
PPT
Sorting Algorithms for data struture prog
Madhumitha J
 
PPTX
Chapter 8 Sorting in the context of DSA.pptx
Dibyesh1
 
PPTX
Parallel Sorting Algorithms. Quicksort. Merge sort. List Ranking
SukhrobAtoev2
 
PPTX
Sorting algorithms
Maher Alshammari
 
PPT
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
PPTX
Sorting and hashing concepts
LJ Projects
 
PPTX
Sorting and hashing concepts
LJ Projects
 
PPT
Data Structure (MC501)
Kamal Singh Lodhi
 
PPT
Searching Sorting-SELECTION ,BUBBBLE.ppt
kunalpatil5661
 
PDF
Sorting algorithms bubble sort to merge sort.pdf
AyeshaMazhar21
 
PPTX
Radix and Merge Sort
Gelo Maribbay
 
Sorting
BHARATH KUMAR
 
Class13_Quicksort_Algorithm.pdf
AkashSingh625550
 
Algorithms and Data Structures - Parahyangan Catholic University Credit Lionov
Pratik Parmar
 
03_sorting and it's types with example .ppt
vanshii9976
 
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
quicksortnmsd cmz ,z m,zmm,mbfjjjjhjhfjsg
RafishaikIT02044
 
sorting-160810203705.pptx
VarchasvaTiwari2
 
SORT AND SEARCH ARRAY WITH WITH C++.pptx
narifmsit18seecs
 
my docoment
NeeshanYonzan
 
Sorting Algorithms for data struture prog
Madhumitha J
 
Chapter 8 Sorting in the context of DSA.pptx
Dibyesh1
 
Parallel Sorting Algorithms. Quicksort. Merge sort. List Ranking
SukhrobAtoev2
 
Sorting algorithms
Maher Alshammari
 
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
Sorting and hashing concepts
LJ Projects
 
Sorting and hashing concepts
LJ Projects
 
Data Structure (MC501)
Kamal Singh Lodhi
 
Searching Sorting-SELECTION ,BUBBBLE.ppt
kunalpatil5661
 
Sorting algorithms bubble sort to merge sort.pdf
AyeshaMazhar21
 
Radix and Merge Sort
Gelo Maribbay
 
Ad

More from Dr.Umadevi V (10)

PPT
Data Structures 5
Dr.Umadevi V
 
PPT
Data Structures 4
Dr.Umadevi V
 
PPT
Data Structures 3
Dr.Umadevi V
 
PPT
Data Structures 2
Dr.Umadevi V
 
PPT
Data Structures
Dr.Umadevi V
 
PPT
computer architecture 4
Dr.Umadevi V
 
PPT
Computer architecture 3
Dr.Umadevi V
 
PPT
computer architecture
Dr.Umadevi V
 
PPT
computer architecture
Dr.Umadevi V
 
PPTX
Multiple access techniques for wireless communication
Dr.Umadevi V
 
Data Structures 5
Dr.Umadevi V
 
Data Structures 4
Dr.Umadevi V
 
Data Structures 3
Dr.Umadevi V
 
Data Structures 2
Dr.Umadevi V
 
Data Structures
Dr.Umadevi V
 
computer architecture 4
Dr.Umadevi V
 
Computer architecture 3
Dr.Umadevi V
 
computer architecture
Dr.Umadevi V
 
computer architecture
Dr.Umadevi V
 
Multiple access techniques for wireless communication
Dr.Umadevi V
 
Ad

Recently uploaded (20)

PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PDF
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PPTX
nutriquiz grade 4.pptx...............................................
ferdinandsanbuenaven
 
PPTX
Nutrition Month 2025 TARP.pptx presentation
FairyLouHernandezMej
 
PPTX
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
PPTX
ENGLISH LEARNING ACTIVITY SHE W5Q1.pptxY
CHERIEANNAPRILSULIT1
 
PPTX
Latest Features in Odoo 18 - Odoo slides
Celine George
 
PPTX
Blanket Order in Odoo 17 Purchase App - Odoo Slides
Celine George
 
PPTX
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
PPTX
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
PPTX
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PPTX
Folding Off Hours in Gantt View in Odoo 18.2
Celine George
 
PDF
07.15.2025 - Managing Your Members Using a Membership Portal.pdf
TechSoup
 
PPTX
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
PPTX
Accounting Skills Paper-I, Preparation of Vouchers
Dr. Sushil Bansode
 
PPTX
SCHOOL-BASED SEXUAL HARASSMENT PREVENTION AND RESPONSE WORKSHOP
komlalokoe
 
PPTX
Nutri-QUIZ-Bee-Elementary.pptx...................
ferdinandsanbuenaven
 
PPTX
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
PPTX
classroom based quiz bee.pptx...................
ferdinandsanbuenaven
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
BÀI TẬP BỔ TRỢ THEO LESSON TIẾNG ANH - I-LEARN SMART WORLD 7 - CẢ NĂM - CÓ ĐÁ...
Nguyen Thanh Tu Collection
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
nutriquiz grade 4.pptx...............................................
ferdinandsanbuenaven
 
Nutrition Month 2025 TARP.pptx presentation
FairyLouHernandezMej
 
Views on Education of Indian Thinkers Mahatma Gandhi.pptx
ShrutiMahanta1
 
ENGLISH LEARNING ACTIVITY SHE W5Q1.pptxY
CHERIEANNAPRILSULIT1
 
Latest Features in Odoo 18 - Odoo slides
Celine George
 
Blanket Order in Odoo 17 Purchase App - Odoo Slides
Celine George
 
ROLE OF ANTIOXIDANT IN EYE HEALTH MANAGEMENT.pptx
Subham Panja
 
Optimizing Cancer Screening With MCED Technologies: From Science to Practical...
i3 Health
 
CLEFT LIP AND PALATE: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
Folding Off Hours in Gantt View in Odoo 18.2
Celine George
 
07.15.2025 - Managing Your Members Using a Membership Portal.pdf
TechSoup
 
How to Configure Storno Accounting in Odoo 18 Accounting
Celine George
 
Accounting Skills Paper-I, Preparation of Vouchers
Dr. Sushil Bansode
 
SCHOOL-BASED SEXUAL HARASSMENT PREVENTION AND RESPONSE WORKSHOP
komlalokoe
 
Nutri-QUIZ-Bee-Elementary.pptx...................
ferdinandsanbuenaven
 
How to Configure Access Rights of Manufacturing Orders in Odoo 18 Manufacturing
Celine George
 
classroom based quiz bee.pptx...................
ferdinandsanbuenaven
 

Data Structures 6

  • 1. Data Structures & Algorithm Sorting I Session VI Dr. V.Umadevi M.Sc(CS &IT). M.Tech (IT)., M.Phil., PhD., D.Litt., Director, Department of Computer Science, Jairams Arts and Science College, Karur.
  • 2. Data Structures & Algorithm Sorting I • Introduction to Sorting • Exchange Sort – Bubble sort – Quick Sorts • Selection and Tree Sorting – Straight Selection Sort – Heap Sort
  • 3. Data Structures & Algorithm Sorting General Def : Arrange the data in some appropriate order according to some key. Examples: • An English dictionary, in which all words are arranged in alphabetic order. • A phone directory, in which phone numbers are listed in some order. • Sorting is the fundamental algorithmic problem in computer science. • Learning the different sorting algorithms is like learning scales for a musician. • Formal Def : Given a sequence of numbers <x1, x2, ..., xn>, a sorting algorithm must compute a permutation <x'1, x'2, ..., x'n> such that x'1 ≤ x'2≤ ... ≤ x'n
  • 4. Data Structures & AlgorithmExchange Sorts Bubble Sort • This sort is oldest and simplest sort in use. • Its is the slowest sort. • Works by comparing each item in the list with the item next to it, swapping them if required. • Algorithm repeat this process until it makes a pass all the way through the list without swapping any items. • Causes larger values to “Sink" to the end of the list while smaller values “bubble" towards the beginning of the list. • Bubble sort is generally considered to be the most inefficient sorting algorithm in common usage. • Under best-case conditions (the list is already sorted), the bubble sort can approach a constant O(n) level of complexity. Pros: Simplicity and ease of implementation. Cons: Horribly inefficient.
  • 5. Data Structures & Algorithm void bubbleSort(int numbers[], int array_size) { int i, j, temp; for (i = (array_size - 1); i >= 0; i--) { for (j = 1; j <= i; j++) { if (numbers[j-1] > numbers[j]) { temp = numbers[j-1]; numbers[j-1] = numbers[j]; numbers[j] = temp; } } } } Source code for Bubble sort
  • 6. Data Structures & AlgorithmExample: 1 2 3 4 5 6 7 // Positions ------------- 4 6 2 5 7 3 4 // Initial sequence 4 2 5 6 3 4 7 // Swapped: 2-3, 3-4, 5-6, 6-7; last_swap=6 2 4 5 3 4 6 7 // Swapped: 1-2, 4-5, 5-6; last_swap=5 2 4 3 4 5 6 7 // Swapped: 3-4, 4-5; last_swap=4 2 3 4 4 5 6 7 // Swapped: 2-3; last_swap=2 2 3 4 4 5 6 7 // No swapping; last_swap=0; end • Analysis: Best case performing one pass which require n-1 comparisons • Consequently best case is O(n). • Worst case performance of bubble sort is n(n-1)/ 2 comparison and exchange • Average case is analysis is O(n2 ). • Average number of comparison and exchanges are both O(n2 ). Bubble Sort Analysis
  • 7. Data Structures & AlgorithmQuick Sort • Invented in 1960 by C. A. R. Hoare • Popular and well investigated • Easy to be implemented and improved • Quick sort is an in-place, divide-and-conquer, massively recursive sort. • Recursive algorithm consists of four steps: 1. If there are one or less elements in the array to be sorted, return immediately. 2. Pick an element in the array to serve as a "pivot" point. (Usually the left- most element in the array is used.) 3. Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot. 4. Recursively repeat the algorithm for both halves of the original array.
  • 8. Data Structures & Algorithm Initial Step - First Partition Sort Left Partition in the same way • Partition array into two segments. • First segment all elements are less than or equal to the pivot value. • Second segment all elements are greater or equal to the pivot value. • Sort the two segments recursively. • Pivot can only be found by scanning the whole array and this would slow down the algorithm. • Quick sort is fastest on average, but sometimes unbalanced partitions can lead to very slow sorting. • The best sorting algorithm when there is no infinite memory space.
  • 9. Data Structures & Algorithm Quicksort Example Analysis • Worst-Case Analysis - the pivot is the smallest element, all the time (requires N recursive call of quicksort O(N)with comparison for a level). So the algorithm O(N2 )will be run in a time. • Best-Case Analysis - the pivot is in the middle, all the time. The running time is . O(N Log N) • Average-Case Analysis - each of the sizes for array (s1) is equally likely. The running time for this case is also O(N Log N) . Pros: Extremely fast. Cons: Very complex algorithm, massively recursive.
  • 10. Data Structures & Algorithmvoid quickSort(int numbers[], int array_size) { q_sort(numbers, 0, array_size - 1); } void q_sort(int numbers[], int left, int right) { int pivot, l_hold, r_hold; l_hold = left; r_hold = right; pivot = numbers[left]; while (left < right) { while ((numbers[right] >= pivot) && (left < right)) right--; if (left != right) { numbers[left] = numbers[right]; left++; } while ((numbers[left] <= pivot) && (left < right)) left++; if (left != right) { numbers[right] = numbers[left]; right--; } } numbers[left] = pivot; pivot = left; left = l_hold; right = r_hold; if (left < pivot) q_sort(numbers, left, pivot-1); if (right > pivot) q_sort(numbers, pivot+1, right); } Code For Quick Sort
  • 11. Data Structures & Algorithm Analysis of Exchange Sorts Exchange Sorts Running Time Algorithms Best Case Average Case Worst Case Bubble Sort O(n2 ) O(n2 ) O(n2 ) Quick Sort O(n Log n) O(n Log n) O(n2 )
  • 12. Data Structures & AlgorithmStraight Selection Sort • Selection sort is one in which successive elements are selected in order and placed into their proper sorted positions. • Elements of the input may have to be preprocessed to make the ordered selection possible. • Def: An algorithm which orders items by repeatedly looking through remaining items to find the least one and moving it to a final location. • Select successive elements in ascending order and place them into their proper position. – Find the smallest element from the array, and exchange it with the first element. – Find the second smallest element, and exchange it with the second element. – Repeat until sorted in proper order. – Searching the smallest key in the record is called pass
  • 13. Data Structures & Algorithm • 42 23 74 11 65 58 94 36 99 87 //Input • [11 ] 23 74 42 65 58 94 36 99 87 • [11 23 ] 74 42 65 58 94 36 99 87 • [11 23 36 ] 42 65 58 94 74 99 87 • [11 23 36 42 ] 65 58 94 74 99 87 • [11 23 36 42 58 ] 65 94 74 99 87 • [11 23 36 42 58 65 ] 94 74 99 87 • [11 23 36 42 58 65 74 ] 94 99 87 • [11 23 36 42 58 65 74 87 ] 99 94 • [11 23 36 42 58 65 74 87 94 ] 99 • 11 23 36 42 58 65 74 87 94 99 //Output • Selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Example of Selection Sort
  • 14. Data Structures & Algorithm •Starting near the top of the array extract the 3. •Then the above elements are shifted down until we find the correct place to insert the 3. •This process repeats in Figure(b) with the next number. • Finally, in Figure(c) complete the sort by inserting 2 in the correct place.
  • 15. Data Structures & Algorithm • N-1 pass is required in order to perform the sort. • During the Ist pass in which the record with the smallest key is found n-1 records are compared. • In general for ith pass of the sort n-I comparisons are required. • Total number of comparisons is • Σn-1 n-I =n(n-1)/2 • i=1 • Therefore the number of comparison is proportional to n2 i.e O(n2 ) • Selection sort has a complexity of O(n2). Pros: Simple and easy to implement. Cons: Inefficient for large lists, so similar to the more efficient insertion sort that the insertion sort should be used in its place. Analysis of Selection Sort
  • 16. Data Structures & Algorithm selection( int a[], int N) /* in C */ /* sort a[1..N], NB. 1 to N */ { int i, j, smallest, aSmallest, temp; for (i=1; i < N; i++) { /* invariant: a[1..i-1] sorted and elements a[1..i-1] <= a[i..N] */ smallest = i; /* find smallest in a[i..N] */ aSmallest = a[i]; for(j=i+1; j <= N; j++) /* a[smallest] is the least element in a[i..j-1] */ if ( a[j] < aSmallest ) { smallest=j; aSmallest=a[j]; } /* a[smallest] is the least element in a[i..j] */ temp=a[i]; a[i]=a[smallest]; a[smallest]=temp; /*swap*/ /* a[1..i] sorted and elements a[1..i] <= a[i+1..N] */ } /* a[1..N-1] sorted and elements a[1..N-1] <= a[N] */ /* i.e. a[1..N] sorted. */ Source Code for Selection Sort
  • 17. Data Structures & Algorithm Heap Sort • Elegant and efficient, widely used. • No extra memory is needed. • Heap sort is based on a tree structure that reflects the packing order in a corporate hierarchy. • This method has two phases. • First the tree representing file is converted to heap • Second stage output sequence is generated in decreasing order • A heap is complete binary tree in which each node satisfies the heap condition represented as an array. Def- a heap is a list in which each entry contains a key and for all positions k in the list, the key at position k is at least as large as the keys in positions 2k and 2k+1 provided these positions exist in the list. • A complete binary tree is said to satisfy the heap condition if the key of each node is greater than or equal to the key in its children, thus the root node will have the largest key value.
  • 18. Data Structures & Algorithm Analysis of Heap sort • Elegant and efficient, widely used. • No extra memory is needed. • On average, Heap sort is third place in speed. • But inner loop is a bit longer than that of Quick Sort, about twice as slow as Quick Sort on the average. • Building of the heap uses at most 2N comparisons, • In the worst case, at most 2n log n - O(n) comparisons are used by heapsort. • Good performance (NlogN) is guaranteed.
  • 19. Data Structures & Algorithm Example of Heap Sort
  • 20. Data Structures & Algorithm
  • 21. Data Structures & Algorithm void heapSort(int numbers[], int array_size) { int i, temp; for (i = (array_size / 2)-1; i >= 0; i--) siftDown(numbers, i, array_size); for (i = array_size-1; i >= 1; i--) { temp = numbers[0]; numbers[0] = numbers[i]; numbers[i] = temp; siftDown(numbers, 0, i-1); } } void siftDown(int numbers[], int root, int bottom) { int done, maxChild, temp; done = 0; while ((root*2 <= bottom) && (!done)) { if (root*2 == bottom) maxChild = root * 2; else if (numbers[root * 2] > numbers[root * 2 + 1]) maxChild = root * 2; else maxChild = root * 2 + 1; if (numbers[root] < numbers[maxChild]) { temp = numbers[root]; numbers[root] = numbers[maxChild]; numbers[maxChild] = temp; root = maxChild; } else done = 1; } }