SlideShare a Scribd company logo
Algorithm,
Review,
Sorting




Merewood, Rowan
Comparing Algorithms

Big   O   notation for:

Running Time – best / average / worst
Memory Usage



                                             2
1      →       n      →     nlogn        →   n



      Also: stability and adaptability
Insertion Sort
           Loop through the whole array

 Compare the current element to the previous one
      If it's in order, carry on



   If it's not:
      Extract it from the array

                   Loop back through the array
                   to find its correct position
Insertion Sort
  function insertionSort(array $a) {
    for ($i = 1; $i < count($a); $i++) {
       if ($a[$i] > $a[$i-1]) {
         continue;
       }

          $tmp = $a[$i];
          $j = $i - 1;

          while($j >= 0 && $a[$j] > $tmp) {
            $a[$j+1] = $a[$j];
            $j--;
          }
          $a[$j+1] = $tmp;
      }

      return $a;
  }
Insertion Sort
                          Running time

             Best: O(n)    Ave. / Worst: O(n2)



               Memory usage: O(n)




   Adaptive, Stable, In-place and On-line
Bubble Sort


                   Loop through the whole array

 Compare the current element to the next

         If they're not in order, swap them round




          Repeat until no swaps are needed
Bubble Sort
 function bubbleSort(array $a) {
   for ($i = count($a); $i > 0; $i--) {
      $swapped = false;
      for ($j = 0; $j < $i-1; $j++) {
        if ($a[$j] > $a[$j+1]) {
           $tmp = $a[$j];
           $a[$j] = $a[$j+1];
           $a[$j+1] = $tmp;
           $swapped = true;
        }
      }

         if (!$swapped) {
           return $a;
         }
     }
 }
Bubble Sort
          Running time:

                  Best: O(n)    Ave. / Worst: O(n2)



                   Memory usage: O(n)

"the bubble sort seems to have nothing to recommend it,
except a catchy name and the fact that it leads to
some interesting theoretical problems"
                                         – Donald Knuth
   More writes, more swaps, etc...
Quick Sort
Divide the array in two, creating a “pivot” value

    Move any value lower than the pivot
    to the left array


Move any value higher than the pivot
to the right array




            Recursively repeat the same operation
            on both arrays
Quick Sort
 function quickSort(array &$a, $left, $right) {
   $pivot = $a[ceil(($left + $right) / 2)];
   $i = $left;
   $j = $right;
   while ($i <= $j) {
      while ($a[$i] < $pivot) $i++;
      while ($a[$j] > $pivot) $j--;
      if ($i <= $j) {
        $tmp = $a[$i];
        $a[$i++] = $a[$j];
        $a[$j--] = $tmp;
      }
   }
   if ($left < $j) quickSort($a, $left, $j);
   if ($i < $right) quickSort($a, $i, $right);
   return $a;
 }
Quick Sort
      Running time:

     Best/Ave: O(n log n)    Worst: O(n2)



               Memory usage: O(n)   [well sort of...]


      Easily parallelized

          Used by PHP's sort()

    Optimisations on: picking a pivot point,
    storage options and recursion
Heap Sort
  A heap is a specific type of binary tree

       In a heap, the parent node is always
       greater than the child


If you convert your array to a heap,
the root of the heap will be the greatest value




 Extract that value, then
 convert the rest of the array to a heap again
Heap Sort

function heapSort(array $a) {
  $size = count($a);
  for ($i = round(($size / 2))-1; $i >= 0; $i--)
     siftDown($a, $i, $size);

    for ($i = $size-1; $i >= 1; $i--) {
      $tmp = $a[0];
      $a[0] = $a[$i];
      $a[$i] = $tmp;
      siftDown($a, 0, $i-1);
    }
    return $a;
}
Heap Sort
   function siftDown(array &$a, $root, $bottom) {
     $done = false;
     while (($root*2 <= $bottom) && (!$done))
     {
        if ($root*2 == $bottom)
          $maxChild = $root * 2;
        elseif ($a[$root * 2] > $a[$root * 2 + 1])
          $maxChild = $root * 2;
        else
          $maxChild = $root * 2 + 1;

           if ($a[$root] < $a[$maxChild]) {
             $tmp = $a[$root];
             $a[$root] = $a[$maxChild];
             $a[$maxChild] = $tmp;
             $root = $maxChild;
           } else $done = true;
       }
   }
Heap Sort


      Running time: O(n log n) ← every time



$h = new SplMinHeap();

foreach ($unsorted as $val) $h->insert($val);

$h->top();

while($h->valid()) {
  echo $h->current()."n";
  $h->next();
}
Counting Sort
Find the highest and lowest values in the array
and calculate the range


Create another 0-filled array
the size of the range


Populate that with a count of the instances of
each value in the array


Now loop through the values in the range again
Populating a final array with the
Relevant number of instances of the value
Counting Sort
 function countingSort(array $a) {
    $size = count($a);
    $min = $max = $a[0];
    for($i = 1; $i < $size; $i++) {
       if ($a[$i] < $min)
          $min = $a[$i];
       elseif ($a[$i] > $max)
          $max = $a[$i];
    }
    $range = $max - $min + 1;
    $count = array();
    for($i = 0; $i < $range; $i++)
       $count[$i] = 0;
    for($i = 0; $i < $size; $i++)
       $count[ $a[$i] - $min ]++;
    $z = 0;
    for($i = $min; $i <= $max; $i++)
       for($j = 0; $j < $count[ $i - $min ]; $j++)
          $a[$z++] = $i;
    return $a;
 }
Counting Sort


                         Running time: O(n+c)

However, if c is large this is silly


Especially on memory usage!




             Sorting a list of exam grades
Alogrithm Ages
Insertion Sort ← optimised in 1959 (Shell Sort)

Counting Sort ← invented in 1954 (Harold H. Seward)

Bubble Sort ← improved in 1980 (Comb Sort)

Quick Sort ← developed in 1960 (C. A. R. Hoare)

Heap Sort ← improved in the '60s (Robert Floyd)

Oh, and there's Radix Sort ← used by
            Herman Hollerith in 1887
Sorted.

More Related Content

What's hot (17)

PPTX
Switching from java to groovy
Paul Woods
 
PDF
ScalaBlitz
Aleksandar Prokopec
 
PDF
A bit about Scala
Vladimir Parfinenko
 
PDF
Introduction to Scala
Aleksandar Prokopec
 
PDF
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
PDF
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Mauricio (Salaboy) Salatino
 
PDF
Scala Parallel Collections
Aleksandar Prokopec
 
PDF
Hammurabi
Mario Fusco
 
PDF
Drools5 Community Training HandsOn 1 Drools DRL Syntax
Mauricio (Salaboy) Salatino
 
PDF
Perl6 a whistle stop tour
Simon Proctor
 
PPTX
Perl6 a whistle stop tour
Simon Proctor
 
PPTX
Python built in functions
Rakshitha S
 
PDF
Type classes 101 - classification beyond inheritance
Alexey Raga
 
PDF
Statistical computing 01
Kevin Chun-Hsien Hsu
 
PPTX
하스켈 프로그래밍 입문 3
Kwang Yul Seo
 
PPT
Groovy unleashed
Isuru Samaraweera
 
PDF
SAT/SMT solving in Haskell
Masahiro Sakai
 
Switching from java to groovy
Paul Woods
 
A bit about Scala
Vladimir Parfinenko
 
Introduction to Scala
Aleksandar Prokopec
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
Ashal aka JOKER
 
Drools5 Community Training Module 3 Drools Expert DRL Syntax
Mauricio (Salaboy) Salatino
 
Scala Parallel Collections
Aleksandar Prokopec
 
Hammurabi
Mario Fusco
 
Drools5 Community Training HandsOn 1 Drools DRL Syntax
Mauricio (Salaboy) Salatino
 
Perl6 a whistle stop tour
Simon Proctor
 
Perl6 a whistle stop tour
Simon Proctor
 
Python built in functions
Rakshitha S
 
Type classes 101 - classification beyond inheritance
Alexey Raga
 
Statistical computing 01
Kevin Chun-Hsien Hsu
 
하스켈 프로그래밍 입문 3
Kwang Yul Seo
 
Groovy unleashed
Isuru Samaraweera
 
SAT/SMT solving in Haskell
Masahiro Sakai
 

Similar to Algorithm, Review, Sorting (20)

PPTX
2.Problem Solving Techniques and Data Structures.pptx
Ganesh Bhosale
 
PPT
Lecture 21 Survey of Sorting.ppt ggggggggggg
ahmadusmani321
 
PPTX
sorting-160810203705.pptx
VarchasvaTiwari2
 
PPTX
Sorting2
Saurabh Mishra
 
ODP
Intro to Sorting + Insertion Sort
Nicholas Case
 
PPT
Arrays in php
Laiby Thomas
 
PPTX
All Searching and Sorting Techniques in Data Structures
sonalishinge2015
 
PPTX
searching in data structure.pptx
chouguleamruta24
 
PDF
Quick sort,bubble sort,heap sort and merge sort
abhinavkumar77723
 
PPTX
Lecture 11.2 : sorting
Vivek Bhargav
 
PDF
Chapter Two.pdf
abay golla
 
PPTX
Chapter 2. data structure and algorithm
SolomonEndalu
 
PPTX
Insertion Sorting
FarihaHabib123
 
PPTX
Searching,sorting
LavanyaJ28
 
PPTX
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
PPTX
9.Sorting & Searching
Mandeep Singh
 
PPSX
Data Structure and Algorithm Chapter 2.ppsx Chapter 2.ppsx
SolomonEndalu
 
PPT
Counting Sort Lowerbound
despicable me
 
PPTX
Different Searching and Sorting Methods.pptx
Minakshee Patil
 
2.Problem Solving Techniques and Data Structures.pptx
Ganesh Bhosale
 
Lecture 21 Survey of Sorting.ppt ggggggggggg
ahmadusmani321
 
sorting-160810203705.pptx
VarchasvaTiwari2
 
Sorting2
Saurabh Mishra
 
Intro to Sorting + Insertion Sort
Nicholas Case
 
Arrays in php
Laiby Thomas
 
All Searching and Sorting Techniques in Data Structures
sonalishinge2015
 
searching in data structure.pptx
chouguleamruta24
 
Quick sort,bubble sort,heap sort and merge sort
abhinavkumar77723
 
Lecture 11.2 : sorting
Vivek Bhargav
 
Chapter Two.pdf
abay golla
 
Chapter 2. data structure and algorithm
SolomonEndalu
 
Insertion Sorting
FarihaHabib123
 
Searching,sorting
LavanyaJ28
 
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
9.Sorting & Searching
Mandeep Singh
 
Data Structure and Algorithm Chapter 2.ppsx Chapter 2.ppsx
SolomonEndalu
 
Counting Sort Lowerbound
despicable me
 
Different Searching and Sorting Methods.pptx
Minakshee Patil
 
Ad

More from Rowan Merewood (8)

PDF
Sensible scaling
Rowan Merewood
 
PDF
Estimation or, "How to Dig your Grave"
Rowan Merewood
 
PDF
A Dependency Injection Primer
Rowan Merewood
 
PDF
TDD and Getting Paid
Rowan Merewood
 
PDF
Practical Applications of Zend_Acl
Rowan Merewood
 
PDF
Living With Legacy Code
Rowan Merewood
 
ODP
Tools and Talent
Rowan Merewood
 
ODP
State Machines to State of the Art
Rowan Merewood
 
Sensible scaling
Rowan Merewood
 
Estimation or, "How to Dig your Grave"
Rowan Merewood
 
A Dependency Injection Primer
Rowan Merewood
 
TDD and Getting Paid
Rowan Merewood
 
Practical Applications of Zend_Acl
Rowan Merewood
 
Living With Legacy Code
Rowan Merewood
 
Tools and Talent
Rowan Merewood
 
State Machines to State of the Art
Rowan Merewood
 
Ad

Algorithm, Review, Sorting

  • 2. Comparing Algorithms Big O notation for: Running Time – best / average / worst Memory Usage 2 1 → n → nlogn → n Also: stability and adaptability
  • 3. Insertion Sort Loop through the whole array Compare the current element to the previous one If it's in order, carry on If it's not: Extract it from the array Loop back through the array to find its correct position
  • 4. Insertion Sort function insertionSort(array $a) { for ($i = 1; $i < count($a); $i++) { if ($a[$i] > $a[$i-1]) { continue; } $tmp = $a[$i]; $j = $i - 1; while($j >= 0 && $a[$j] > $tmp) { $a[$j+1] = $a[$j]; $j--; } $a[$j+1] = $tmp; } return $a; }
  • 5. Insertion Sort Running time Best: O(n) Ave. / Worst: O(n2) Memory usage: O(n) Adaptive, Stable, In-place and On-line
  • 6. Bubble Sort Loop through the whole array Compare the current element to the next If they're not in order, swap them round Repeat until no swaps are needed
  • 7. Bubble Sort function bubbleSort(array $a) { for ($i = count($a); $i > 0; $i--) { $swapped = false; for ($j = 0; $j < $i-1; $j++) { if ($a[$j] > $a[$j+1]) { $tmp = $a[$j]; $a[$j] = $a[$j+1]; $a[$j+1] = $tmp; $swapped = true; } } if (!$swapped) { return $a; } } }
  • 8. Bubble Sort Running time: Best: O(n) Ave. / Worst: O(n2) Memory usage: O(n) "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems" – Donald Knuth More writes, more swaps, etc...
  • 9. Quick Sort Divide the array in two, creating a “pivot” value Move any value lower than the pivot to the left array Move any value higher than the pivot to the right array Recursively repeat the same operation on both arrays
  • 10. Quick Sort function quickSort(array &$a, $left, $right) { $pivot = $a[ceil(($left + $right) / 2)]; $i = $left; $j = $right; while ($i <= $j) { while ($a[$i] < $pivot) $i++; while ($a[$j] > $pivot) $j--; if ($i <= $j) { $tmp = $a[$i]; $a[$i++] = $a[$j]; $a[$j--] = $tmp; } } if ($left < $j) quickSort($a, $left, $j); if ($i < $right) quickSort($a, $i, $right); return $a; }
  • 11. Quick Sort Running time: Best/Ave: O(n log n) Worst: O(n2) Memory usage: O(n) [well sort of...] Easily parallelized Used by PHP's sort() Optimisations on: picking a pivot point, storage options and recursion
  • 12. Heap Sort A heap is a specific type of binary tree In a heap, the parent node is always greater than the child If you convert your array to a heap, the root of the heap will be the greatest value Extract that value, then convert the rest of the array to a heap again
  • 13. Heap Sort function heapSort(array $a) { $size = count($a); for ($i = round(($size / 2))-1; $i >= 0; $i--) siftDown($a, $i, $size); for ($i = $size-1; $i >= 1; $i--) { $tmp = $a[0]; $a[0] = $a[$i]; $a[$i] = $tmp; siftDown($a, 0, $i-1); } return $a; }
  • 14. Heap Sort function siftDown(array &$a, $root, $bottom) { $done = false; while (($root*2 <= $bottom) && (!$done)) { if ($root*2 == $bottom) $maxChild = $root * 2; elseif ($a[$root * 2] > $a[$root * 2 + 1]) $maxChild = $root * 2; else $maxChild = $root * 2 + 1; if ($a[$root] < $a[$maxChild]) { $tmp = $a[$root]; $a[$root] = $a[$maxChild]; $a[$maxChild] = $tmp; $root = $maxChild; } else $done = true; } }
  • 15. Heap Sort Running time: O(n log n) ← every time $h = new SplMinHeap(); foreach ($unsorted as $val) $h->insert($val); $h->top(); while($h->valid()) { echo $h->current()."n"; $h->next(); }
  • 16. Counting Sort Find the highest and lowest values in the array and calculate the range Create another 0-filled array the size of the range Populate that with a count of the instances of each value in the array Now loop through the values in the range again Populating a final array with the Relevant number of instances of the value
  • 17. Counting Sort function countingSort(array $a) { $size = count($a); $min = $max = $a[0]; for($i = 1; $i < $size; $i++) { if ($a[$i] < $min) $min = $a[$i]; elseif ($a[$i] > $max) $max = $a[$i]; } $range = $max - $min + 1; $count = array(); for($i = 0; $i < $range; $i++) $count[$i] = 0; for($i = 0; $i < $size; $i++) $count[ $a[$i] - $min ]++; $z = 0; for($i = $min; $i <= $max; $i++) for($j = 0; $j < $count[ $i - $min ]; $j++) $a[$z++] = $i; return $a; }
  • 18. Counting Sort Running time: O(n+c) However, if c is large this is silly Especially on memory usage! Sorting a list of exam grades
  • 19. Alogrithm Ages Insertion Sort ← optimised in 1959 (Shell Sort) Counting Sort ← invented in 1954 (Harold H. Seward) Bubble Sort ← improved in 1980 (Comb Sort) Quick Sort ← developed in 1960 (C. A. R. Hoare) Heap Sort ← improved in the '60s (Robert Floyd) Oh, and there's Radix Sort ← used by Herman Hollerith in 1887