SlideShare a Scribd company logo
Sorting Algorithms Guest Lecturer G. Alan Wang, ABD MIS 531A Fall, 2005
Outline Computation Complexity Simple Sorting Algorithms Bubble Sort Insertion Sort Selection Sort Complex Sorting Algorithms Quick Sort Heap Sort
Computation Complexity Definition: Measure the efficiency of an algorithm in terms of time or space required. Time tends to be more important. The efficiency of an algorithm is always stated as a function of the input size The “Big-O” notation: O( f(n) ) Worst case scenario The  maximum  number of computation steps taken on any input size  n The strategy is to find the closest upper bound of the worst case scenario Upper bound Lower bound Actual function
Time Complexity We assume each operation in a program take one time unit. int sum (int n) { int partial_sum = 0; for (int i = 1; i <= n; i++) partial_sum = partial_sum + (i * i ); return partial_sum; } Time Units to Compute ------------------------------- 1 for the assignment. 1 assignment,  n+1  tests,  and  n  increments. n  loops of 3 units for an  assignment, an addition,  and one multiplication. 1 for the return statement. ---------------------------------------- Total:  1+(1+n+1+n)+3n+1  = 5n+4 = O(n)
Basic Time Complexity Functions In an increasing order of complexity: Constant time: O(1) Logarithmic time: O(log n ) Linear time: O( n ) Polynomial time: O( n 2 ) Exponential time: O(2 n ) Suppose each step takes 1 microseconds (10 -6 ):
Basic Time Complexity Functions
Bubble Sort Sorting takes an unordered collection and makes it an ordered one. Bubble sort algorithm*: Compare adjacent elements. If the first is greater than the second, swap them.  Do this for each pair of adjacent elements, starting with the first two and ending with the last two. At this point the last element should be the greatest.  Repeat the steps for all elements except the last one.  Keep repeating for one fewer element each time, until you have no more pairs to compare  Time complexity: O( n 2 ) Demo:  http://www.cs.princeton.edu/~ah/alg_anim/gawain-4.0/BubbleSort.html Example:  Sort the list {12, 5, 7, 9, 2, 6} *: Excerpted from WIKIPEDIA, http://en.wikipedia.org/wiki/Bubble_sort
Insertion Sort Algorithm*: Start with the result being the first element of the input; Loop over the input array until it is empty, &quot;removing&quot; the first remaining (leftmost) element; Compare the removed element against the current result, starting from the highest (rightmost) element, and working left towards the lowest element; If the removed input element is lower than the current result element, copy that value into the following element to make room for the new element below, and repeat with the next lowest result element; Otherwise, the new element is in the correct location; save it in the cell left by copying the last examined result up, and start again from step 2 with the next input element. Time complexity: O( n 2 ) Demo:  http://web.engr.oregonstate.edu/~minoura/cs162/javaProgs/sort/InsertSort.html   Example:  Sort the list {12, 5, 7, 9, 2, 6} *: Excerpted from WIKIPEDIA, http://en.wikipedia.org/wiki/Bubble_sort
Selection Sort Algorithm: Pass through elements sequentially; In the  i th  pass, we select the element with the lowest value in A[i] through A[n], then swap the lowest value with A[i]. Time complexity: O( n 2 ) Demo:  http:// www.cosc.canterbury.ac.nz/people/mukundan/dsal/SSort.html   Example: Sort the list {25, 57, 48, 37, 12}
Quick Sort Quick sort, also known as partition sort, sorts by employing a divide-and-conquer strategy. Algorithm: Pick an pivot element from the input; Partition all other input elements such that elements less than the pivot come before the pivot and those greater than the pivot come after it (equal values can go either way); Recursively sort the list of elements before the pivot and the list of elements after the pivot. The recursion terminates when a list contains zero or one element. Example: Sort the list {25, 57, 48, 37, 12}
Quick Sort Quick sort, also known as partition sort, sorts by employing a divide-and-conquer strategy. Algorithm: Pick an pivot element from the input; Partition all other input elements such that elements less than the pivot come before the pivot and those greater than the pivot come after it (equal values can go either way); Recursively sort the list of elements before the pivot and the list of elements after the pivot. The recursion terminates when a list contains zero or one element. Time complexity: O( n log n ) or O( n 2 ) Demo:  http:// pages.stern.nyu.edu/~panos/java/Quicksort /   Example: Sort the list {25, 57, 48, 37, 12}
Heap Definition: Almost Complete Binary Tree ( ACBT )  Descending heap:  ACBT + every node value ≤parent node value Ascending heap:  ACBT + every node value    parent node value
Heap Sort Heapify phase:  Create a descending heap Add element to a binary tree from top to bottom and from left to right When adding a new element, if the element is out of order, perform “sift-up” operations (a sequence of swap with parent) Example: {25, 57, 48, 37, 12}
Heap Sort (Cont’d) Sorting phase Work backwards from bottom to top and from right to left Swap current element with root For the new root, perform “sift-down” operations (swap with the larger son).
Heap Sort (Cont’d) Time complexity:  Heapify: O( n log 2 n ) Sorting: O( n log 2 n ) Overall: O( n log 2 n ) + O( n log 2 n ) = O( n log 2 n )
Questions
ACBT A binary tree with nodes numbered 1 to n (top  bottom, left  right). All the leaves are in the bottom two levels. All the leaves are in the leftmost possible positions. [k/2] is the farther of  k K ’s   2 sons : 2k  and  2k+1 BACK
Ad

More Related Content

What's hot (20)

Queues
QueuesQueues
Queues
Lovely Professional University
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
Kaushal Shah
 
Binary Search
Binary SearchBinary Search
Binary Search
kunj desai
 
Searching algorithms
Searching algorithmsSearching algorithms
Searching algorithms
Trupti Agrawal
 
Linear and Binary search
Linear and Binary searchLinear and Binary search
Linear and Binary search
Nisha Soms
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
Muhammad Hammad Waseem
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
Rahul Jamwal
 
Binary search
Binary searchBinary search
Binary search
AparnaKumari31
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
DurgaDeviCbit
 
Searching and sorting
Searching  and sortingSearching  and sorting
Searching and sorting
PoojithaBollikonda
 
Stack
StackStack
Stack
Zaid Shabbir
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
SHAKOOR AB
 
Doubly linked list (animated)
Doubly linked list (animated)Doubly linked list (animated)
Doubly linked list (animated)
DivyeshKumar Jagatiya
 
Stacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
Zidny Nafan
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
Tareq Hasan
 
Ppt bubble sort
Ppt bubble sortPpt bubble sort
Ppt bubble sort
prabhakar jalasutram
 
Insertion sort algorithm power point presentation
Insertion  sort algorithm power point presentation Insertion  sort algorithm power point presentation
Insertion sort algorithm power point presentation
University of Science and Technology Chitttagong
 
Selection sort
Selection sortSelection sort
Selection sort
smlagustin
 

Similar to Sorting Algorithms (20)

The Stack in data structures .ppt
The Stack in data structures         .pptThe Stack in data structures         .ppt
The Stack in data structures .ppt
donemoremaregere376
 
Lecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptxLecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptx
JosephKariuki46
 
algorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptxalgorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptx
kassahungebrie
 
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
DSA_Ques ewoifhjerofhefhehfreofheek.pptxDSA_Ques ewoifhjerofhefhehfreofheek.pptx
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
arnab13984
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdf
Nash229987
 
lecture to proide studeny with F-k-sorting.ppt
lecture to proide studeny with F-k-sorting.pptlecture to proide studeny with F-k-sorting.ppt
lecture to proide studeny with F-k-sorting.ppt
indranilbanerji25109
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
LegesseSamuel
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
SushantRaj25
 
3.ppt
3.ppt3.ppt
3.ppt
ganeshyadav184128
 
Lecture k-sorting
Lecture k-sortingLecture k-sorting
Lecture k-sorting
Vijayaraj Raj
 
02 stackqueue
02 stackqueue02 stackqueue
02 stackqueue
Chandan Kumar
 
Stack & Queue in Data Structure and Algorithms
Stack & Queue in Data Structure and AlgorithmsStack & Queue in Data Structure and Algorithms
Stack & Queue in Data Structure and Algorithms
Virgo Lay
 
Selection sort
Selection sortSelection sort
Selection sort
asra khan
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
maamir farooq
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
Rajkiran Nadar
 
Sorting
SortingSorting
Sorting
Ghaffar Khan
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
The presention is about the queue data structure
The presention is about the queue data structureThe presention is about the queue data structure
The presention is about the queue data structure
gaurav77712
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
DrRanjeetKumar51721
 
The Stack in data structures .ppt
The Stack in data structures         .pptThe Stack in data structures         .ppt
The Stack in data structures .ppt
donemoremaregere376
 
Lecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptxLecture 5_ Sorting and order statistics.pptx
Lecture 5_ Sorting and order statistics.pptx
JosephKariuki46
 
algorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptxalgorithm assignmenteeeeeee.pptx
algorithm assignmenteeeeeee.pptx
kassahungebrie
 
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
DSA_Ques ewoifhjerofhefhehfreofheek.pptxDSA_Ques ewoifhjerofhefhehfreofheek.pptx
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
arnab13984
 
03-data-structures.pdf
03-data-structures.pdf03-data-structures.pdf
03-data-structures.pdf
Nash229987
 
lecture to proide studeny with F-k-sorting.ppt
lecture to proide studeny with F-k-sorting.pptlecture to proide studeny with F-k-sorting.ppt
lecture to proide studeny with F-k-sorting.ppt
indranilbanerji25109
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
LegesseSamuel
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
SushantRaj25
 
Stack & Queue in Data Structure and Algorithms
Stack & Queue in Data Structure and AlgorithmsStack & Queue in Data Structure and Algorithms
Stack & Queue in Data Structure and Algorithms
Virgo Lay
 
Selection sort
Selection sortSelection sort
Selection sort
asra khan
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
maamir farooq
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
Rajkiran Nadar
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
The presention is about the queue data structure
The presention is about the queue data structureThe presention is about the queue data structure
The presention is about the queue data structure
gaurav77712
 
Ad

Recently uploaded (20)

Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Ad

Sorting Algorithms

  • 1. Sorting Algorithms Guest Lecturer G. Alan Wang, ABD MIS 531A Fall, 2005
  • 2. Outline Computation Complexity Simple Sorting Algorithms Bubble Sort Insertion Sort Selection Sort Complex Sorting Algorithms Quick Sort Heap Sort
  • 3. Computation Complexity Definition: Measure the efficiency of an algorithm in terms of time or space required. Time tends to be more important. The efficiency of an algorithm is always stated as a function of the input size The “Big-O” notation: O( f(n) ) Worst case scenario The maximum number of computation steps taken on any input size n The strategy is to find the closest upper bound of the worst case scenario Upper bound Lower bound Actual function
  • 4. Time Complexity We assume each operation in a program take one time unit. int sum (int n) { int partial_sum = 0; for (int i = 1; i <= n; i++) partial_sum = partial_sum + (i * i ); return partial_sum; } Time Units to Compute ------------------------------- 1 for the assignment. 1 assignment, n+1 tests, and n increments. n loops of 3 units for an assignment, an addition, and one multiplication. 1 for the return statement. ---------------------------------------- Total: 1+(1+n+1+n)+3n+1 = 5n+4 = O(n)
  • 5. Basic Time Complexity Functions In an increasing order of complexity: Constant time: O(1) Logarithmic time: O(log n ) Linear time: O( n ) Polynomial time: O( n 2 ) Exponential time: O(2 n ) Suppose each step takes 1 microseconds (10 -6 ):
  • 7. Bubble Sort Sorting takes an unordered collection and makes it an ordered one. Bubble sort algorithm*: Compare adjacent elements. If the first is greater than the second, swap them. Do this for each pair of adjacent elements, starting with the first two and ending with the last two. At this point the last element should be the greatest. Repeat the steps for all elements except the last one. Keep repeating for one fewer element each time, until you have no more pairs to compare Time complexity: O( n 2 ) Demo: http://www.cs.princeton.edu/~ah/alg_anim/gawain-4.0/BubbleSort.html Example: Sort the list {12, 5, 7, 9, 2, 6} *: Excerpted from WIKIPEDIA, http://en.wikipedia.org/wiki/Bubble_sort
  • 8. Insertion Sort Algorithm*: Start with the result being the first element of the input; Loop over the input array until it is empty, &quot;removing&quot; the first remaining (leftmost) element; Compare the removed element against the current result, starting from the highest (rightmost) element, and working left towards the lowest element; If the removed input element is lower than the current result element, copy that value into the following element to make room for the new element below, and repeat with the next lowest result element; Otherwise, the new element is in the correct location; save it in the cell left by copying the last examined result up, and start again from step 2 with the next input element. Time complexity: O( n 2 ) Demo: http://web.engr.oregonstate.edu/~minoura/cs162/javaProgs/sort/InsertSort.html Example: Sort the list {12, 5, 7, 9, 2, 6} *: Excerpted from WIKIPEDIA, http://en.wikipedia.org/wiki/Bubble_sort
  • 9. Selection Sort Algorithm: Pass through elements sequentially; In the i th pass, we select the element with the lowest value in A[i] through A[n], then swap the lowest value with A[i]. Time complexity: O( n 2 ) Demo: http:// www.cosc.canterbury.ac.nz/people/mukundan/dsal/SSort.html Example: Sort the list {25, 57, 48, 37, 12}
  • 10. Quick Sort Quick sort, also known as partition sort, sorts by employing a divide-and-conquer strategy. Algorithm: Pick an pivot element from the input; Partition all other input elements such that elements less than the pivot come before the pivot and those greater than the pivot come after it (equal values can go either way); Recursively sort the list of elements before the pivot and the list of elements after the pivot. The recursion terminates when a list contains zero or one element. Example: Sort the list {25, 57, 48, 37, 12}
  • 11. Quick Sort Quick sort, also known as partition sort, sorts by employing a divide-and-conquer strategy. Algorithm: Pick an pivot element from the input; Partition all other input elements such that elements less than the pivot come before the pivot and those greater than the pivot come after it (equal values can go either way); Recursively sort the list of elements before the pivot and the list of elements after the pivot. The recursion terminates when a list contains zero or one element. Time complexity: O( n log n ) or O( n 2 ) Demo: http:// pages.stern.nyu.edu/~panos/java/Quicksort / Example: Sort the list {25, 57, 48, 37, 12}
  • 12. Heap Definition: Almost Complete Binary Tree ( ACBT ) Descending heap: ACBT + every node value ≤parent node value Ascending heap: ACBT + every node value  parent node value
  • 13. Heap Sort Heapify phase: Create a descending heap Add element to a binary tree from top to bottom and from left to right When adding a new element, if the element is out of order, perform “sift-up” operations (a sequence of swap with parent) Example: {25, 57, 48, 37, 12}
  • 14. Heap Sort (Cont’d) Sorting phase Work backwards from bottom to top and from right to left Swap current element with root For the new root, perform “sift-down” operations (swap with the larger son).
  • 15. Heap Sort (Cont’d) Time complexity: Heapify: O( n log 2 n ) Sorting: O( n log 2 n ) Overall: O( n log 2 n ) + O( n log 2 n ) = O( n log 2 n )
  • 17. ACBT A binary tree with nodes numbered 1 to n (top  bottom, left  right). All the leaves are in the bottom two levels. All the leaves are in the leftmost possible positions. [k/2] is the farther of k K ’s 2 sons : 2k and 2k+1 BACK