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)

PPT
Binary Search
kunj desai
 
PPTX
Merge Sort
Nikhil Sonkamble
 
PPTX
Binary search
AparnaKumari31
 
PPTX
Merge sort and quick sort
Shakila Mahjabin
 
PPTX
Data Structures (CS8391)
Elavarasi K
 
PPTX
Bubble Sort Algorithm Presentation
AhmedAlbutty
 
PDF
linear search and binary search
Zia Ush Shamszaman
 
PPTX
Sorting in python
Simplilearn
 
PPT
Merge sort
Vidushi Pathak
 
PPTX
Sorting Algorithms
Pranay Neema
 
PPTX
linked list in data structure
shameen khan
 
PPTX
Deque and its applications
Jsaddam Hussain
 
PPT
Bubble sort
Manek Ar
 
PPTX
heap Sort Algorithm
Lemia Algmri
 
PPTX
Bubble sort
Rashmi R Upadhya
 
PPTX
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
PPTX
Bubble sort | Data structure |
MdSaiful14
 
PPSX
Data Structure (Queue)
Adam Mukharil Bachtiar
 
PPTX
Introduction to stack
vaibhav2910
 
PPTX
Presentation-Merge Sort
Md Showrov Ahmed
 
Binary Search
kunj desai
 
Merge Sort
Nikhil Sonkamble
 
Binary search
AparnaKumari31
 
Merge sort and quick sort
Shakila Mahjabin
 
Data Structures (CS8391)
Elavarasi K
 
Bubble Sort Algorithm Presentation
AhmedAlbutty
 
linear search and binary search
Zia Ush Shamszaman
 
Sorting in python
Simplilearn
 
Merge sort
Vidushi Pathak
 
Sorting Algorithms
Pranay Neema
 
linked list in data structure
shameen khan
 
Deque and its applications
Jsaddam Hussain
 
Bubble sort
Manek Ar
 
heap Sort Algorithm
Lemia Algmri
 
Bubble sort
Rashmi R Upadhya
 
Stacks IN DATA STRUCTURES
Sowmya Jyothi
 
Bubble sort | Data structure |
MdSaiful14
 
Data Structure (Queue)
Adam Mukharil Bachtiar
 
Introduction to stack
vaibhav2910
 
Presentation-Merge Sort
Md Showrov Ahmed
 

Similar to Sorting Algorithms (20)

PPT
The Stack in data structures .ppt
donemoremaregere376
 
PPTX
Lecture 5_ Sorting and order statistics.pptx
JosephKariuki46
 
PPTX
algorithm assignmenteeeeeee.pptx
kassahungebrie
 
PDF
5.1 Priority Queues.pdf 5.1 Priority Queues.pdf5.1 Priority Queues.pdf5.1 Pri...
BeHappy728244
 
PPTX
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
arnab13984
 
PDF
03-data-structures.pdf
Nash229987
 
PPT
lecture to proide studeny with F-k-sorting.ppt
indranilbanerji25109
 
PPT
Algorithms with-java-advanced-1.0
BG Java EE Course
 
PPT
Advanced s and s algorithm.ppt
LegesseSamuel
 
PPT
lecture-k-sorting.ppt
SushantRaj25
 
PPT
Lecture k-sorting
Vijayaraj Raj
 
PDF
02 stackqueue
Chandan Kumar
 
PPTX
Stack & Queue in Data Structure and Algorithms
Virgo Lay
 
DOC
Selection sort
asra khan
 
PDF
Data structures arrays
maamir farooq
 
PPTX
Data structure , stack , queue
Rajkiran Nadar
 
PPT
Sorting
Ghaffar Khan
 
PPT
Stack linked list
bhargav0077
 
PPTX
The presention is about the queue data structure
gaurav77712
 
The Stack in data structures .ppt
donemoremaregere376
 
Lecture 5_ Sorting and order statistics.pptx
JosephKariuki46
 
algorithm assignmenteeeeeee.pptx
kassahungebrie
 
5.1 Priority Queues.pdf 5.1 Priority Queues.pdf5.1 Priority Queues.pdf5.1 Pri...
BeHappy728244
 
DSA_Ques ewoifhjerofhefhehfreofheek.pptx
arnab13984
 
03-data-structures.pdf
Nash229987
 
lecture to proide studeny with F-k-sorting.ppt
indranilbanerji25109
 
Algorithms with-java-advanced-1.0
BG Java EE Course
 
Advanced s and s algorithm.ppt
LegesseSamuel
 
lecture-k-sorting.ppt
SushantRaj25
 
Lecture k-sorting
Vijayaraj Raj
 
02 stackqueue
Chandan Kumar
 
Stack & Queue in Data Structure and Algorithms
Virgo Lay
 
Selection sort
asra khan
 
Data structures arrays
maamir farooq
 
Data structure , stack , queue
Rajkiran Nadar
 
Sorting
Ghaffar Khan
 
Stack linked list
bhargav0077
 
The presention is about the queue data structure
gaurav77712
 
Ad

Recently uploaded (20)

PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
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