Download Analysis of Algorithms - Advanced Programming - Lecture Slides and more Slides Computer Science in PDF only on Docsity! Analysis of Algorithms Introduction using Insertion Sort Docsity.com Characteristics of Algorithms • Algorithms are precise. Each step has a clearly defined meaning; “Deterministic” • Algorithms are effective. The task is always done as required; “Correct” • Algorithms have a finite number of steps; Algorithms must terminate. How do you know? Docsity.com Example: sorting numbered cards 23 17 45 18 12 22 1 2 6 5 4 3 1 2 6 5 4 3 Docsity.com Example: sorting numbered cards 23 17 45 18 12 22 1 2 6 5 4 3 1 2 6 5 4 3 Docsity.com Example: sorting numbered cards 23 17 45 18 12 22 1 2 6 5 4 3 1 2 6 5 4 3 Docsity.com Example: sorting numbered cards 18 12 22 17 23 45 1 2 6 5 4 3 1 2 6 5 4 3 Docsity.com Expressing computer algorithms • It should be expressed in a language more precise, less ambiguous, and more compact than a “natural language” such as English; • Algorithms are usually written in a pseudocode and later translated to a real programming language. • Sometimes algorithms are “flowcharted” using HIPO (Hierarchical Input, Processing, and Output) symbols. Docsity.com Insertion Sort in Pseudocode B[1] = A[1] for j = 2 to n { i = j - 1 while 0 < i and A[j] < B[i] i = i - 1 for k = j downto i + 2 B[k] = B[k-1] B[i+1] = A[j] } In se rt io n o f jt h c ar d Finding the place to insert A[j] Shifting a part of array B Inserting A[j] A is an array of numbers of length n, B is an empty array Docsity.com Insertion Sort Analysis (cont.) • Best Case: Array already sorted, )1(0)1(0)1()1()( 87654321 nccnccncncnccnT 8643186432 * cccccnccccc ban 1jt for all j. (Linear in n) Docsity.com Insertion Sort Analysis (cont.) • Worst Case: Array in reverse order, Note that 2 )1( 1 2 )1( )1()( 54321 nn c nn cncnccnT )1( 2 )1( 1 2 )1( 876 nc nn c nn c ncccccccncccc 8765432 2 7654 2/2/2/2/2/2/2/2/ cbnanccccc 286431 We are usually interested in the worst-case running time jt j for all j. (quadratic in n) Docsity.com