SlideShare ist ein Scribd-Unternehmen logo
1 von 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;
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Data Structure
Introduction to Data Structure Introduction to Data Structure
Introduction to Data Structure Prof Ansari
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 dsHanif Durad
 
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
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)PRABHAHARAN429
 
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
 

Was ist angesagt? (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
 

Ă„hnlich wie Data Structures 6

Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfAkashSingh625550
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptxVarchasvaTiwari2
 
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
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)Kamal Singh Lodhi
 
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
 
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
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptxAnSHiKa187943
 

Ă„hnlich wie 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
 
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
 
sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
 

Mehr von Dr.Umadevi V

Data Structures 5
Data Structures 5Data Structures 5
Data Structures 5Dr.Umadevi V
 
Data Structures 4
Data Structures 4Data Structures 4
Data Structures 4Dr.Umadevi V
 
Data Structures 3
Data Structures 3Data Structures 3
Data Structures 3Dr.Umadevi V
 
Data Structures 2
Data Structures 2Data Structures 2
Data Structures 2Dr.Umadevi V
 
Data Structures
Data StructuresData Structures
Data StructuresDr.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
 

Mehr von 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
 

KĂĽrzlich hochgeladen

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 

KĂĽrzlich hochgeladen (20)

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 

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