SlideShare a Scribd company logo
Insertion Sort &
        Shellsort
By: Andy Le
CS146 – Dr. Sin Min Lee
Spring 2004
Outline
 Importance of Sorting
 Insertion Sort
     Explanation
     Runtime
     Advantage and Disadvantage
     Walk through example
 Shell Sort
     History
     Explanation
     Runtime
     Advantage and Disadvantage
     Walk through example
Why we do sorting?
 Commonly encountered programming task in
  computing.
 Examples of sorting:
   List containing exam scores sorted from Lowest to
    Highest or from Highest to Lowest
   List containing words that were misspelled and be
    listed in alphabetical order.
   List of student records and sorted by student
    number or alphabetically by first or last name.
Why we do sorting?

 Searching for an element in an array will
  be more efficient. (example: looking up
  for information like phone number).
 It’s always nice to see data in a sorted
  display. (example: spreadsheet or
  database application).
 Computers sort things much faster.
History of Sorting

 Sorting is one of the most important
  operations performed by computers. In
  the days of magnetic tape storage before
  modern databases, database updating
  was done by sorting transactions and
  merging them with a master file.
History of Sorting

 It's still important for presentation of data
  extracted from databases: most people
  prefer to get reports sorted into some
  relevant order before flipping through
  pages of data!
Insertion Sort
 Insertion sort keeps making the left side of the
  array sorted until the whole array is sorted. It
  sorts the values seen far away and repeatedly
  inserts unseen values in the array into the left
  sorted array.
 It is the simplest of all sorting algorithms.
 Although it has the same complexity as Bubble
  Sort, the insertion sort is a little over twice as
  efficient as the bubble sort.
Insertion Sort

 Real life example:
   An example of an insertion sort occurs in
    everyday life while playing cards. To sort the
    cards in your hand you extract a card, shift
    the remaining cards, and then insert the
    extracted card in the correct place. This
    process is repeated until all the cards are in
    the correct sequence.
Insertion Sort runtimes

 Best case: O(n). It occurs when the data
  is in sorted order. After making one pass
  through the data and making no
  insertions, insertion sort exits.
 Average case: θ(n^2) since there is a
  wide variation with the running time.
 Worst case: O(n^2) if the numbers were
  sorted in reverse order.
Empirical Analysis of Insertion Sort




   The graph demonstrates the n^2 complexity of the insertion sort.

Source: http://linux.wku.edu/~lamonml/algor/sort/insertion.html
Insertion Sort

 The insertion sort is a good choice for
  sorting lists of a few thousand items or
  less.
Insertion Sort

 The insertion sort shouldn't be used for
  sorting lists larger than a couple
  thousand items or repetitive sorting of
  lists larger than a couple hundred items.
Insertion Sort

 This algorithm is much simpler than the
  shell sort, with only a small trade-off in
  efficiency. At the same time, the insertion
  sort is over twice as fast as the bubble
  sort.
Advantage of Insertion Sort

 The advantage of Insertion Sort is that it
  is relatively simple and easy to
  implement.
Disadvantage of Insertion Sort

 The disadvantage of Insertion Sort is that
  it is not efficient to operate with a large
  list or input size.
Insertion Sort Example

      Sort: 34 8 64 51 32 21
 34 8 64 51 32 21
  The algorithm sees that 8 is smaller than 34
   so it swaps.
 8 34 64 51 32 21
  51 is smaller than 64, so they swap.
 8 34 51 64 32 21
Insertion Sort Example
      Sort: 34 8 64 51 32 21
 8 34 51 64 32 21 (from previous slide)
   The algorithm sees 32 as another smaller
    number and moves it to its appropriate
    location between 8 and 34.
 8 32 34 51 64 21
   The algorithm sees 21 as another smaller
    number and moves into between 8 and 32.
 Final sorted numbers:
 8 21 32 34 51 64
Shellsort
 Founded by Donald Shell and named the
  sorting algorithm after himself in 1959.
 1st algorithm to break the quadratic time barrier
  but few years later, a sub quadratic time bound
  was proven
 Shellsort works by comparing elements that
  are distant rather than adjacent elements in an
  array or list where adjacent elements are
  compared.
Shellsort

 Shellsort uses a sequence h1, h2, …, ht
  called the increment sequence. Any
  increment sequence is fine as long as h 1
  = 1 and some other choices are better
  than others.
Shellsort

 Shellsort makes multiple passes through
  a list and sorts a number of equally sized
  sets using the insertion sort.
Shellsort

 Shellsort improves on the efficiency of
  insertion sort by quickly shifting values to
  their destination.
Shellsort

 Shellsort is also known as diminishing
  increment sort.
 The distance between comparisons
  decreases as the sorting algorithm runs
  until the last phase in which adjacent
  elements are compared
Shellsort

 After each phase and some increment
  hk, for every i, we have a[ i ] ≤ a [ i + hk ]
  all elements spaced hk apart are sorted.
 The file is said to be hk – sorted.
Empirical Analysis of Shellsort




 Source: http://linux.wku.edu/~lamonml/algor/sort/shell.html
Empirical Analysis of Shellsort
        (Advantage)
 Advantage of Shellsort is that its only
  efficient for medium size lists. For bigger
  lists, the algorithm is not the best choice.
  Fastest of all O(N^2) sorting algorithms.
 5 times faster than the bubble sort and a
  little over twice as fast as the insertion
  sort, its closest competitor.
Empirical Analysis of Shellsort
       (Disadvantage)
 Disadvantage of Shellsort is that it is a complex
  algorithm and its not nearly as efficient as the
  merge, heap, and quick sorts.
 The shell sort is still significantly slower than
  the merge, heap, and quick sorts, but its
  relatively simple algorithm makes it a good
  choice for sorting lists of less than 5000 items
  unless speed important. It's also an excellent
  choice for repetitive sorting of smaller lists.
Shellsort Best Case

 Best Case: The best case in the shell
  sort is when the array is already sorted in
  the right order. The number of
  comparisons is less.
Shellsort Worst Case

 The running time of Shellsort depends on
  the choice of increment sequence.
 The problem with Shell’s increments is
  that pairs of increments are not
  necessarily relatively prime and smaller
  increments can have little effect.
Shellsort Examples
      Sort: 18 32 12 5 38 33 16 2
        8 Numbers to be sorted, Shell’s increment will be floor(n/2)
         * floor(8/2)  floor(4) = 4

         increment 4: 1         2        3         4      (visualize underlining)

                          18 32 12 5 38 33 16            2

Step 1) Only look at 18 and 38 and sort in order ;
18 and 38 stays at its current position because they are in order.
Step 2) Only look at 32 and 33 and sort in order ;
32 and 33 stays at its current position because they are in order.
Step 3) Only look at 12 and 16 and sort in order ;
12 and 16 stays at its current position because they are in order.
Step 4) Only look at 5 and 2 and sort in order ;
2 and 5 need to be switched to be in order.
Shellsort Examples (con’t)
      Sort: 18 32 12 5 38 33 16 2
Resulting numbers after increment 4 pass:
      18 32 12 2          38 33 16 5
* floor(4/2)  floor(2) = 2
 increment 2:    1   2

            18       32        12       2        38        33       16          5
  Step 1) Look at 18, 12, 38, 16 and sort them in their appropriate location:

            12       38        16       2        18        33       38          5
  Step 2) Look at 32, 2, 33, 5 and sort them in their appropriate location:
            12       2         16       5        18        32       38          33
Shellsort Examples (con’t)
         Sort: 18 32 12 5 38 33 16 2
* floor(2/2)  floor(1) = 1
 increment 1: 1
         12       2           16   5    18    32      38      33

         2        5           12   16   18    32      33     38


   The last increment or phase of Shellsort is basically an Insertion
   Sort algorithm.
Additional Online References

 Spark Notes (From Barnes & Noble):
   http://www.sparknotes.com/cs/
The End

More Related Content

What's hot

Insertion sort
Insertion sortInsertion sort
Insertion sort
MYER301
 
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
 
AVL Tree
AVL TreeAVL Tree
Linear search-and-binary-search
Linear search-and-binary-searchLinear search-and-binary-search
Linear search-and-binary-search
International Islamic University
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
Jsaddam Hussain
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
Ninad Mankar
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
Mohamed Loey
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
SIVASHANKARIRAJAN
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
Rojan Pariyar
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
FarihaHabib123
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Queues
QueuesQueues
Queue
QueueQueue
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
Umesh Kumar
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
Dr Shashikant Athawale
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
harsh kothari
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
Shubham Dwivedi
 
Bubble sort
Bubble sortBubble sort
Bubble sort
Manek Ar
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
Himanshu Kesharwani
 

What's hot (20)

Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Linear search-and-binary-search
Linear search-and-binary-searchLinear search-and-binary-search
Linear search-and-binary-search
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
 
sorting and its types
sorting and its typessorting and its types
sorting and its types
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems Webinar : P, NP, NP-Hard , NP - Complete problems
Webinar : P, NP, NP-Hard , NP - Complete problems
 
Queues
QueuesQueues
Queues
 
Queue
QueueQueue
Queue
 
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
PPT On Sorting And Searching Concepts In Data Structure | In Programming Lang...
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Fractional Knapsack Problem
Fractional Knapsack ProblemFractional Knapsack Problem
Fractional Knapsack Problem
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
 

Viewers also liked

Insertion sort
Insertion sortInsertion sort
Insertion sort
Rajendran
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
aditya raj
 
Insertion Sort Algorithm
Insertion Sort AlgorithmInsertion Sort Algorithm
Insertion Sort Algorithm
Gail Carmichael
 
Selection Sort - Vipin Ramola
Selection Sort - Vipin RamolaSelection Sort - Vipin Ramola
Selection Sort - Vipin Ramola
Dipayan Sarkar
 
Insertion Sort
Insertion SortInsertion Sort
Insertion Sort
Brett Duncan
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
almaqboli
 
Advanced Sorting Algorithms
Advanced Sorting AlgorithmsAdvanced Sorting Algorithms
Advanced Sorting Algorithms
Damian T. Gordon
 

Viewers also liked (7)

Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Insertion Sort Algorithm
Insertion Sort AlgorithmInsertion Sort Algorithm
Insertion Sort Algorithm
 
Selection Sort - Vipin Ramola
Selection Sort - Vipin RamolaSelection Sort - Vipin Ramola
Selection Sort - Vipin Ramola
 
Insertion Sort
Insertion SortInsertion Sort
Insertion Sort
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Advanced Sorting Algorithms
Advanced Sorting AlgorithmsAdvanced Sorting Algorithms
Advanced Sorting Algorithms
 

Similar to Sorting Techniques

Is sort andy-le
Is sort andy-leIs sort andy-le
Is sort andy-le
Sumedha
 
sorting_part1.ppt
sorting_part1.pptsorting_part1.ppt
sorting_part1.ppt
ReehaamMalikArain
 
Shell sort
Shell sortShell sort
Shell sort
Rajendran
 
Shell sort
Shell sortShell sort
Shell sort
Rajendran
 
Shell sort in Data Structure Using C
Shell sort in Data Structure Using CShell sort in Data Structure Using C
Shell sort in Data Structure Using C
Ashish Gaurkhede
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
LegesseSamuel
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
ashish bansal
 
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
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
Dr.Umadevi V
 
Sorting Techniques for Data Structures.pptx
Sorting Techniques for Data Structures.pptxSorting Techniques for Data Structures.pptx
Sorting Techniques for Data Structures.pptx
Kalpana Mohan
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
Ain-ul-Moiz Khawaja
 
Algorithim lec1.pptx
Algorithim lec1.pptxAlgorithim lec1.pptx
Algorithim lec1.pptx
rediet43
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
Eman magdy
 
Merge sort analysis and its real time applications
Merge sort analysis and its real time applicationsMerge sort analysis and its real time applications
Merge sort analysis and its real time applications
yazad dumasia
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
Abdii Rashid
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
DrRanjeetKumar51721
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
Muhammad Hammad Waseem
 
Sorting
SortingSorting
Sorting
BHARATH KUMAR
 
Radix and Merge Sort
Radix and Merge SortRadix and Merge Sort
Radix and Merge Sort
Gelo Maribbay
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
SushantRaj25
 

Similar to Sorting Techniques (20)

Is sort andy-le
Is sort andy-leIs sort andy-le
Is sort andy-le
 
sorting_part1.ppt
sorting_part1.pptsorting_part1.ppt
sorting_part1.ppt
 
Shell sort
Shell sortShell sort
Shell sort
 
Shell sort
Shell sortShell sort
Shell sort
 
Shell sort in Data Structure Using C
Shell sort in Data Structure Using CShell sort in Data Structure Using C
Shell sort in Data Structure Using C
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
 
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
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Sorting Techniques for Data Structures.pptx
Sorting Techniques for Data Structures.pptxSorting Techniques for Data Structures.pptx
Sorting Techniques for Data Structures.pptx
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Algorithim lec1.pptx
Algorithim lec1.pptxAlgorithim lec1.pptx
Algorithim lec1.pptx
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
 
Merge sort analysis and its real time applications
Merge sort analysis and its real time applicationsMerge sort analysis and its real time applications
Merge sort analysis and its real time applications
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
Sorting
SortingSorting
Sorting
 
Radix and Merge Sort
Radix and Merge SortRadix and Merge Sort
Radix and Merge Sort
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
 

Recently uploaded

Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 

Recently uploaded (20)

Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 

Sorting Techniques

  • 1. Insertion Sort & Shellsort By: Andy Le CS146 – Dr. Sin Min Lee Spring 2004
  • 2. Outline  Importance of Sorting  Insertion Sort  Explanation  Runtime  Advantage and Disadvantage  Walk through example  Shell Sort  History  Explanation  Runtime  Advantage and Disadvantage  Walk through example
  • 3. Why we do sorting?  Commonly encountered programming task in computing.  Examples of sorting:  List containing exam scores sorted from Lowest to Highest or from Highest to Lowest  List containing words that were misspelled and be listed in alphabetical order.  List of student records and sorted by student number or alphabetically by first or last name.
  • 4. Why we do sorting?  Searching for an element in an array will be more efficient. (example: looking up for information like phone number).  It’s always nice to see data in a sorted display. (example: spreadsheet or database application).  Computers sort things much faster.
  • 5. History of Sorting  Sorting is one of the most important operations performed by computers. In the days of magnetic tape storage before modern databases, database updating was done by sorting transactions and merging them with a master file.
  • 6. History of Sorting  It's still important for presentation of data extracted from databases: most people prefer to get reports sorted into some relevant order before flipping through pages of data!
  • 7. Insertion Sort  Insertion sort keeps making the left side of the array sorted until the whole array is sorted. It sorts the values seen far away and repeatedly inserts unseen values in the array into the left sorted array.  It is the simplest of all sorting algorithms.  Although it has the same complexity as Bubble Sort, the insertion sort is a little over twice as efficient as the bubble sort.
  • 8. Insertion Sort  Real life example:  An example of an insertion sort occurs in everyday life while playing cards. To sort the cards in your hand you extract a card, shift the remaining cards, and then insert the extracted card in the correct place. This process is repeated until all the cards are in the correct sequence.
  • 9. Insertion Sort runtimes  Best case: O(n). It occurs when the data is in sorted order. After making one pass through the data and making no insertions, insertion sort exits.  Average case: θ(n^2) since there is a wide variation with the running time.  Worst case: O(n^2) if the numbers were sorted in reverse order.
  • 10. Empirical Analysis of Insertion Sort The graph demonstrates the n^2 complexity of the insertion sort. Source: http://linux.wku.edu/~lamonml/algor/sort/insertion.html
  • 11. Insertion Sort  The insertion sort is a good choice for sorting lists of a few thousand items or less.
  • 12. Insertion Sort  The insertion sort shouldn't be used for sorting lists larger than a couple thousand items or repetitive sorting of lists larger than a couple hundred items.
  • 13. Insertion Sort  This algorithm is much simpler than the shell sort, with only a small trade-off in efficiency. At the same time, the insertion sort is over twice as fast as the bubble sort.
  • 14. Advantage of Insertion Sort  The advantage of Insertion Sort is that it is relatively simple and easy to implement.
  • 15. Disadvantage of Insertion Sort  The disadvantage of Insertion Sort is that it is not efficient to operate with a large list or input size.
  • 16. Insertion Sort Example  Sort: 34 8 64 51 32 21  34 8 64 51 32 21  The algorithm sees that 8 is smaller than 34 so it swaps.  8 34 64 51 32 21  51 is smaller than 64, so they swap.  8 34 51 64 32 21
  • 17. Insertion Sort Example  Sort: 34 8 64 51 32 21  8 34 51 64 32 21 (from previous slide)  The algorithm sees 32 as another smaller number and moves it to its appropriate location between 8 and 34.  8 32 34 51 64 21  The algorithm sees 21 as another smaller number and moves into between 8 and 32.  Final sorted numbers:  8 21 32 34 51 64
  • 18. Shellsort  Founded by Donald Shell and named the sorting algorithm after himself in 1959.  1st algorithm to break the quadratic time barrier but few years later, a sub quadratic time bound was proven  Shellsort works by comparing elements that are distant rather than adjacent elements in an array or list where adjacent elements are compared.
  • 19. Shellsort  Shellsort uses a sequence h1, h2, …, ht called the increment sequence. Any increment sequence is fine as long as h 1 = 1 and some other choices are better than others.
  • 20. Shellsort  Shellsort makes multiple passes through a list and sorts a number of equally sized sets using the insertion sort.
  • 21. Shellsort  Shellsort improves on the efficiency of insertion sort by quickly shifting values to their destination.
  • 22. Shellsort  Shellsort is also known as diminishing increment sort.  The distance between comparisons decreases as the sorting algorithm runs until the last phase in which adjacent elements are compared
  • 23. Shellsort  After each phase and some increment hk, for every i, we have a[ i ] ≤ a [ i + hk ] all elements spaced hk apart are sorted.  The file is said to be hk – sorted.
  • 24. Empirical Analysis of Shellsort Source: http://linux.wku.edu/~lamonml/algor/sort/shell.html
  • 25. Empirical Analysis of Shellsort (Advantage)  Advantage of Shellsort is that its only efficient for medium size lists. For bigger lists, the algorithm is not the best choice. Fastest of all O(N^2) sorting algorithms.  5 times faster than the bubble sort and a little over twice as fast as the insertion sort, its closest competitor.
  • 26. Empirical Analysis of Shellsort (Disadvantage)  Disadvantage of Shellsort is that it is a complex algorithm and its not nearly as efficient as the merge, heap, and quick sorts.  The shell sort is still significantly slower than the merge, heap, and quick sorts, but its relatively simple algorithm makes it a good choice for sorting lists of less than 5000 items unless speed important. It's also an excellent choice for repetitive sorting of smaller lists.
  • 27. Shellsort Best Case  Best Case: The best case in the shell sort is when the array is already sorted in the right order. The number of comparisons is less.
  • 28. Shellsort Worst Case  The running time of Shellsort depends on the choice of increment sequence.  The problem with Shell’s increments is that pairs of increments are not necessarily relatively prime and smaller increments can have little effect.
  • 29. Shellsort Examples  Sort: 18 32 12 5 38 33 16 2 8 Numbers to be sorted, Shell’s increment will be floor(n/2) * floor(8/2)  floor(4) = 4 increment 4: 1 2 3 4 (visualize underlining) 18 32 12 5 38 33 16 2 Step 1) Only look at 18 and 38 and sort in order ; 18 and 38 stays at its current position because they are in order. Step 2) Only look at 32 and 33 and sort in order ; 32 and 33 stays at its current position because they are in order. Step 3) Only look at 12 and 16 and sort in order ; 12 and 16 stays at its current position because they are in order. Step 4) Only look at 5 and 2 and sort in order ; 2 and 5 need to be switched to be in order.
  • 30. Shellsort Examples (con’t)  Sort: 18 32 12 5 38 33 16 2 Resulting numbers after increment 4 pass: 18 32 12 2 38 33 16 5 * floor(4/2)  floor(2) = 2 increment 2: 1 2 18 32 12 2 38 33 16 5 Step 1) Look at 18, 12, 38, 16 and sort them in their appropriate location: 12 38 16 2 18 33 38 5 Step 2) Look at 32, 2, 33, 5 and sort them in their appropriate location: 12 2 16 5 18 32 38 33
  • 31. Shellsort Examples (con’t)  Sort: 18 32 12 5 38 33 16 2 * floor(2/2)  floor(1) = 1 increment 1: 1 12 2 16 5 18 32 38 33 2 5 12 16 18 32 33 38 The last increment or phase of Shellsort is basically an Insertion Sort algorithm.
  • 32. Additional Online References  Spark Notes (From Barnes & Noble):  http://www.sparknotes.com/cs/