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

More Related Content

What's hot (20)

Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Mohammed Hussein
 
Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithn
Kumar
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
almaqboli
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
Elavarasi K
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
Meghaj Mallick
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data Structure
Jeanie Arnoco
 
Shell sort
Shell sortShell sort
Shell sort
Rajendran
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
Drishti Bhalla
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
TharuniDiddekunta
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
Searching and sorting
Searching  and sortingSearching  and sorting
Searching and sorting
PoojithaBollikonda
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
SHAKOOR AB
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
Monalisa Patel
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
Rahul Jamwal
 
Stack project
Stack projectStack project
Stack project
Amr Aboelgood
 
Data structure by Digvijay
Data structure by DigvijayData structure by Digvijay
Data structure by Digvijay
Digvijay Singh Karakoti
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
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
 

Similar to Sorting Algorithms (20)

sorting-160810203705.pptx
sorting-160810203705.pptxsorting-160810203705.pptx
sorting-160810203705.pptx
VarchasvaTiwari2
 
Different Searching and Sorting Methods.pptx
Different Searching and Sorting Methods.pptxDifferent Searching and Sorting Methods.pptx
Different Searching and Sorting Methods.pptx
Minakshee Patil
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sorting
Vivek Bhargav
 
Sorting pnk
Sorting pnkSorting pnk
Sorting pnk
pinakspatel
 
Quicksort
QuicksortQuicksort
Quicksort
Gayathri Gaayu
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptxDSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
suryatom5775
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Unit vii sorting
Unit   vii sorting Unit   vii sorting
Unit vii sorting
Tribhuvan University
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
Afaq Mansoor Khan
 
Sorting
SortingSorting
Sorting
BHARATH KUMAR
 
Sorting2
Sorting2Sorting2
Sorting2
Saurabh Mishra
 
L 14-ct1120
L 14-ct1120L 14-ct1120
L 14-ct1120
Zia Ush Shamszaman
 
All Searching and Sorting Techniques in Data Structures
All Searching and Sorting Techniques in Data StructuresAll Searching and Sorting Techniques in Data Structures
All Searching and Sorting Techniques in Data Structures
sonalishinge2015
 
03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt
vanshii9976
 
03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
SajalFayyaz
 
Sorting-Algorithms-A-Comprehensive-Guide.pptx
Sorting-Algorithms-A-Comprehensive-Guide.pptxSorting-Algorithms-A-Comprehensive-Guide.pptx
Sorting-Algorithms-A-Comprehensive-Guide.pptx
ReemEmad26
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptx
Dr.Shweta
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
sonugupta
 
Different Searching and Sorting Methods.pptx
Different Searching and Sorting Methods.pptxDifferent Searching and Sorting Methods.pptx
Different Searching and Sorting Methods.pptx
Minakshee Patil
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sorting
Vivek Bhargav
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptxDSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
suryatom5775
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
All Searching and Sorting Techniques in Data Structures
All Searching and Sorting Techniques in Data StructuresAll Searching and Sorting Techniques in Data Structures
All Searching and Sorting Techniques in Data Structures
sonalishinge2015
 
03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt03_sorting and it's types with example .ppt
03_sorting and it's types with example .ppt
vanshii9976
 
03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt03_sorting123456789454545454545444543.ppt
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
SajalFayyaz
 
Sorting-Algorithms-A-Comprehensive-Guide.pptx
Sorting-Algorithms-A-Comprehensive-Guide.pptxSorting-Algorithms-A-Comprehensive-Guide.pptx
Sorting-Algorithms-A-Comprehensive-Guide.pptx
ReemEmad26
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptx
Dr.Shweta
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
sonugupta
 
Ad

Recently uploaded (20)

Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptxFIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Data Validation and System Interoperability
Data Validation and System InteroperabilityData Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptxFIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
“From Enterprise to Makers: Driving Vision AI Innovation at the Extreme Edge,...
Edge AI and Vision Alliance
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
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