SlideShare a Scribd company logo
1 of 21
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

Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure Prof Ansari
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structuressshhzap
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil duttAnil Dutt
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)Arvind Devaraj
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structureBiswajit Mandal
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1Kumar
 
Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in Onejehan1987
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureZaid Shabbir
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its FundamentalsHitesh Mohapatra
 
Data structures Basics
Data structures BasicsData structures Basics
Data structures BasicsDurgaDeviCbit
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structuresKuber Chandra
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structureAshim Lamichhane
 

What's hot (20)

Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure
 
Data Structures & Algorithm design using C
Data Structures & Algorithm design using C Data Structures & Algorithm design using C
Data Structures & Algorithm design using C
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
Chapter 2.2 data structures
Chapter 2.2 data structuresChapter 2.2 data structures
Chapter 2.2 data structures
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)
 
Data structures
Data structuresData structures
Data structures
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)
 
Elementary data structure
Elementary data structureElementary data structure
Elementary data structure
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
Lecture 1 and 2
Lecture 1 and 2Lecture 1 and 2
Lecture 1 and 2
 
Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in One
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Data structures Basics
Data structures BasicsData structures Basics
Data structures Basics
 
Presentation on Elementary data structures
Presentation on Elementary data structuresPresentation on Elementary data structures
Presentation on Elementary data structures
 
Data Structure
Data StructureData Structure
Data Structure
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 

Similar to Data Structures 6

Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfAkashSingh625550
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing conceptsLJ Projects
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing conceptsLJ Projects
 
Radix and Merge Sort
Radix and Merge SortRadix and Merge Sort
Radix and Merge SortGelo Maribbay
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using javaNarayan Sau
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptxDeepakM509554
 
Algorithm analysis (All in one)
Algorithm analysis (All in one)Algorithm analysis (All in one)
Algorithm analysis (All in one)jehan1987
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfArumugam90
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sortingFadhil Ismail
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresPRIANKA R
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharpMicheal Ogundero
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0BG Java EE Course
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure Eman magdy
 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2Deepak John
 

Similar to Data Structures 6 (20)

Sorting
SortingSorting
Sorting
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
 
my docoment
my docomentmy docoment
my docoment
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing concepts
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing concepts
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)
 
Radix and Merge Sort
Radix and Merge SortRadix and Merge Sort
Radix and Merge Sort
 
Data structure and algorithm using java
Data structure and algorithm using javaData structure and algorithm using java
Data structure and algorithm using java
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
 
Algorithm analysis (All in one)
Algorithm analysis (All in one)Algorithm analysis (All in one)
Algorithm analysis (All in one)
 
DSJ_Unit I & II.pdf
DSJ_Unit I & II.pdfDSJ_Unit I & II.pdf
DSJ_Unit I & II.pdf
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structures
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
 
Analysis and design of algorithms part2
Analysis and design of algorithms part2Analysis and design of algorithms part2
Analysis and design of algorithms part2
 

More from Dr.Umadevi V

computer architecture 4
computer architecture 4 computer architecture 4
computer architecture 4 Dr.Umadevi V
 
Computer architecture 3
Computer architecture 3Computer architecture 3
Computer architecture 3Dr.Umadevi V
 
computer architecture
computer architecture computer architecture
computer architecture Dr.Umadevi V
 
computer architecture
computer architecture computer architecture
computer architecture Dr.Umadevi V
 
Multiple access techniques for wireless communication
Multiple access techniques for wireless communicationMultiple access techniques for wireless communication
Multiple access techniques for wireless communicationDr.Umadevi V
 

More from Dr.Umadevi V (10)

Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5
 
Data Structures 4
Data Structures 4Data Structures 4
Data Structures 4
 
Data Structures 3
Data Structures 3Data Structures 3
Data Structures 3
 
Data Structures 2
Data Structures 2Data Structures 2
Data Structures 2
 
Data Structures
Data StructuresData Structures
Data Structures
 
computer architecture 4
computer architecture 4 computer architecture 4
computer architecture 4
 
Computer architecture 3
Computer architecture 3Computer architecture 3
Computer architecture 3
 
computer architecture
computer architecture computer architecture
computer architecture
 
computer architecture
computer architecture computer architecture
computer architecture
 
Multiple access techniques for wireless communication
Multiple access techniques for wireless communicationMultiple access techniques for wireless communication
Multiple access techniques for wireless communication
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answersdalebeck957
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 

Recently uploaded (20)

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 

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; } }