5_onotation

# Theaveragecaseismuchmorelikethebestcase

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: t pos = i; // Shuffle up all sorted items &gt; arr[i] while(pos &gt; 0 &amp;&amp; arr[pos - 1] &gt; temp){ arr[pos] = arr[pos – 1]; inner loop body  how many times?  pos--; } //while // Insert the current item min: just the test for each  outer loop iteration, n   arr[pos] = temp; } max: i – 1 times for each }  iteration, n * (n – 1) / 2  John Edgar 49 Sorted  Elements 0 1 2 … n‐1 Worst‐case  Search 0 1 2 … n‐1 n(n‐1)/2 Worst‐case  Shuffle 0 1 2 … n‐1 n(n‐1)/2 John Edgar 50 !  The efficiency of insertion sort is affected by  the state of the array to be sorted  !  In the best case the array is already  completely sorted!  !  Requires n comparisons  !  No movement of array elements is required  John Edgar 51 !  In the worst case the array is in reverse order  !  Every item has to be moved all the way to the  front of the array  !  The outer loop runs n‐1 times  ▪  In the first iteration, one comparison and move  ▪  In the last iteration, n‐1 comparisons and moves  ▪  On average, n/2 comparisons and moves  !  For a total of n * (n‐1) / 2 comparisons and moves  John Edgar 52 !  What is the average case cost?  !  Is it closer to the best case?  !  Or the worst case?  !  If random data are sorted, insertion sort is  usually closer to the worst case  !  Around n * (n‐1) / 4 comparisons  !  What is average input for a sorting  algorithm in any case?  John Edgar 53 !  Quicksort is a more efficient sorting algorithm than  either selection or insertion sort  We will go over the basic idea of quicksort and an  example of it  !  See text for details  !  It sorts an array by repeatedly partitioning it  !  John Edgar 55 !  Partitioning is the process of dividing an array into  sections (partitions), based on some criteria  !  &quot;Big&quot; and &quot;small&quot; values  !  Negative and positive numbers  !  Names that begin with a‐m, names that begin with n‐z  !  Darker and lighter pixels  !  Quicksort uses repeated partitioning to sort an array  John Edgar 56 Partition this array into small  and big values using a  partitioning algorithm  31 12 07 23 93 02 11 18 John Edgar 57 Partition this array into small  and big values using a  ...
View Full Document

Ask a homework question - tutors are online