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)

PDF
Python list
Mohammed Sikander
 
PDF
Stack
Zaid Shabbir
 
PPT
Merge sort
Vidushi Pathak
 
PPTX
Quick sort-Data Structure
Jeanie Arnoco
 
PPTX
Collision in Hashing.pptx
NBACriteria2SICET
 
PDF
8 python data structure-1
Prof. Dr. K. Adisesha
 
PDF
sparse matrix in data structure
MAHALAKSHMI P
 
PPTX
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
PPT
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
PDF
linear search and binary search
Zia Ush Shamszaman
 
PDF
Binary search algorithm
maamir farooq
 
PPTX
Python list
ArchanaBhumkar
 
PPTX
Quick Sort
Shweta Sahu
 
PDF
linked lists in data structures
DurgaDeviCbit
 
PDF
Singly linked list
Amar Jukuntla
 
PPTX
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
PPTX
Prims and kruskal algorithms
Saga Valsalan
 
PPTX
Quick sort
Dhruv Sabalpara
 
PPTX
Hash table in data structure and algorithm
Aamir Sohail
 
Python list
Mohammed Sikander
 
Merge sort
Vidushi Pathak
 
Quick sort-Data Structure
Jeanie Arnoco
 
Collision in Hashing.pptx
NBACriteria2SICET
 
8 python data structure-1
Prof. Dr. K. Adisesha
 
sparse matrix in data structure
MAHALAKSHMI P
 
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
linear search and binary search
Zia Ush Shamszaman
 
Binary search algorithm
maamir farooq
 
Python list
ArchanaBhumkar
 
Quick Sort
Shweta Sahu
 
linked lists in data structures
DurgaDeviCbit
 
Singly linked list
Amar Jukuntla
 
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Prims and kruskal algorithms
Saga Valsalan
 
Quick sort
Dhruv Sabalpara
 
Hash table in data structure and algorithm
Aamir Sohail
 

Similar to Sorting Algorithms (20)

PPTX
sorting-160810203705.pptx
VarchasvaTiwari2
 
PPTX
Different Searching and Sorting Methods.pptx
Minakshee Patil
 
PPTX
Lecture 11.2 : sorting
Vivek Bhargav
 
PPTX
Sorting pnk
pinakspatel
 
PPT
Quicksort
Gayathri Gaayu
 
PPTX
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
PPTX
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
suryatom5775
 
PPTX
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
PPTX
Unit vii sorting
Tribhuvan University
 
PPTX
Sorting Algorithms
Afaq Mansoor Khan
 
DOCX
Sorting
BHARATH KUMAR
 
PPTX
Sorting2
Saurabh Mishra
 
PDF
L 14-ct1120
Zia Ush Shamszaman
 
PPTX
All Searching and Sorting Techniques in Data Structures
sonalishinge2015
 
PPT
quicksortnmsd cmz ,z m,zmm,mbfjjjjhjhfjsg
RafishaikIT02044
 
PPT
03_sorting and it's types with example .ppt
vanshii9976
 
PPT
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
PPTX
Data structure.pptx
SajalFayyaz
 
PPT
Lecture 21 Survey of Sorting.ppt ggggggggggg
ahmadusmani321
 
PPTX
Sorting-Algorithms-A-Comprehensive-Guide.pptx
ReemEmad26
 
sorting-160810203705.pptx
VarchasvaTiwari2
 
Different Searching and Sorting Methods.pptx
Minakshee Patil
 
Lecture 11.2 : sorting
Vivek Bhargav
 
Sorting pnk
pinakspatel
 
Quicksort
Gayathri Gaayu
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Radhika Talaviya
 
DSA-sortijejjejjdjjdjdjjsjsjsjsjsjsjng.pptx
suryatom5775
 
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Unit vii sorting
Tribhuvan University
 
Sorting Algorithms
Afaq Mansoor Khan
 
Sorting
BHARATH KUMAR
 
Sorting2
Saurabh Mishra
 
L 14-ct1120
Zia Ush Shamszaman
 
All Searching and Sorting Techniques in Data Structures
sonalishinge2015
 
quicksortnmsd cmz ,z m,zmm,mbfjjjjhjhfjsg
RafishaikIT02044
 
03_sorting and it's types with example .ppt
vanshii9976
 
03_sorting123456789454545454545444543.ppt
ssuser7b9bda1
 
Data structure.pptx
SajalFayyaz
 
Lecture 21 Survey of Sorting.ppt ggggggggggg
ahmadusmani321
 
Sorting-Algorithms-A-Comprehensive-Guide.pptx
ReemEmad26
 
Ad

Recently uploaded (20)

PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Python basic programing language for automation
DanialHabibi2
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
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