Presentation is loading. Please wait.

Presentation is loading. Please wait.

Algorithms and Programming

Similar presentations


Presentation on theme: "Algorithms and Programming"— Presentation transcript:

1 Algorithms and Programming
Chin-Sung Lin Eleanor Roosevelt High School

2 Algorithms and Programming
Types of Algorithms Brute-Force (or Exhaustive Search) Divide and Conquer The Greedy Method Recursion Algorithms of Skyscrapers Project Review of Pseudo Code Decimal-to-Binary Conversion Algorithm Programming: A Crash Course of C Sorting Algorithms and Implementations Searching Algorithms and Implementations

3 Brute-Force Algorithms

4 Brute-Force (or Exhaustive Search)
Brute-force is a straightforward approach to solving a problem, usually directly based on the problem’s statement and definitions of the concepts involved. Try out all possible values or combinations to solve a problem, or try every possible solution to see which is best.

5 Brute-Force (or Exhaustive Search) Example
Try out all possible combinations to open a lock. Try out all possible password values to log into an account.

6 Brute-Force (or Exhaustive Search) Example
Compute an for a given number a and a nonnegative integer n. By the definition of exponentiation, an = a  a    a. Build 250-block skyscraper by adding one block each week. n times

7 Brute-Force (or Exhaustive Search)
Though inefficient in general, the brute-force algorithm should not be overlooked as an important algorithm design strategy for the following reasons: It is applicable to a very wide variety problems, and seems to be the only general approach for all problems. The expense of designing a more efficient algorithm may be unjustifiable if only a few instances of a problem need to be solved and a brute-force algorithm can solve those instances with acceptable speed. It is useful for solving small-size instances of a problem. It can serve as an important theoretical or education purpose, e.g., as a benchmark to judge more efficient alternatives algorithms.

8 Divide and Conquer Algorithms

9 Divide and Conquer Repeatedly reduces an instance of a problem to one or more smaller instances of the same problem (usually recursively) until the instances are small enough to solve easily. The solutions to the subproblems are then combined to give a solution to the original problem.

10 Divide and Conquer The most well known algorithm design strategy:
Divide the problem into two or more smaller subproblems. Conquer the subproblems by solving them recursively. Combine the solutions to the subproblems into the solutions for the original problem.

11 Divide and Conquer Example
Large-integer multiplication (The Grade-School Algorithm) a1 a2 … an x b1 b2 … bn (d10) d11d12 … d1n (d20) d21d22 … d2n … … … … … … … (dn0) dn1dn2 … dnn This process requires n2 single digit multiplications. For 1231  2012, this process requires 16 multiplications.

12 Divide and Conquer Example
Large-integer multiplication (Divide and Conquer Algorithm) 1231  2012 = (12* ) * (20* ) = (12*20)*104 + c1* *12 where c1 = (12+31)*(20+12) – 12*20 – 31*12 = 764 12*20 = (1*10 + 2) * (2*10 + 0) = (1*2)*102 + c2*10 + 2*0 where c2 = (1+2)*(2+0) – 1*2 – 2*0 = 4 31*12 = (3*10 + 1) * (1*10 + 2) = (3*1)*102 + c3*10 + 1*2 where c3 = (3+1)*(1+2) – 3*1 – 1*2 = 7 (12+31)*(20+12) = 43 * 32 = (4*10 + 3) * (3*10 + 2) = (4*3)*102 + c4*10 + 3*2 where c4 = (4+3)*(3+2) – 4*3 – 3*2 = 17 This process requires 9 digit multiplications as opposed to 16.

13 Greedy Algorithms

14 Greedy Algorithms An optimization problem is one in which you want to find, not just a solution, but the best solution. It is not exhaustive, and does not give an accurate answer to many problems. But when it works, it is the fastest method. A greedy algorithm works in phases. At each phase: You take the best you can get right now, without regard for future consequences You hope that by choosing a local optimum at each step, you will end up at a global optimum 2

15 Greedy Algorithm Example
Pay out the exact amount of money using US monetary system. The knapsack problem – Given a set of items, each with a mass and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible.

16 Greedy Algorithm Example
Example: Dijkstra's algorithm (single-source shortest path problem) Works on both directed and undirected graphs. However, all edges must have nonnegative weights. Input: Weighted graph and source vertex (v) such that all edge weights are nonnegative Output: Lengths of shortest paths (or the shortest paths themselves) from a given source vertex (v) to all other vertices

17 Greedy Algorithm Example

18 Greedy Algorithm Example

19 Greedy Algorithm Example

20 Greedy Algorithm Example

21 Greedy Algorithm Example

22 Greedy Algorithm Example

23 Greedy Algorithm Example

24 Greedy Algorithm Example

25 Greedy Algorithm Example

26 Greedy Algorithm Example

27 Recursive Algorithms Recursive Algorithms Recursive Algorithms

28 Recursion A recursive function is one which calls itself. To prevent infinite recursion, you need an if-else statement (of some sort) where one branch makes a recursive call, and the other branch does not.

29 Recursion Dream (problem) { If problems solved return solution else
}

30 Recursion Example Example: Calculate the factorial of N:
N! = N x (N-1) x (N-2) x ……. x 3 x 2 x 1 Traditional algorithm using Loop: Factorial () Let index = 1 Let product = 1 For index = 1 to N   product = product x index      end-For return product

31 Recursion Example Example: Calculate the factorial of N:
N! = N x (N-1) x (N-2) x ……. x 3 x 2 x 1 Recursive algorithm: Factorial(long n) {      if (n==1)          return(n);      else          return(n * factorial(n-1)); }

32 Recursion Example A traditional algorithm for finding the Fibonacci Numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ……) Fibonacci () Input N Let result0 = 0 Let result1 = 1 If N = 1 or N = 2 result = N - 1 else for loop counter = 2 to N – 1 result = result1 + result0 result0 = result1 result1 = result end-for loop end-if output result

33 Recursion Example A recursive algorithm for finding the Fibonacci Numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ……) Fibonacci (N) If N = 1 or N = 2 return (N – 1) else return Fibonacci (N – 1) + Fibonacci (N – 2) end-if

34 Algorithms of Skyscrapers Project

35 Algorithms of Skyscrapers Project
Rules: Using prefabricated-modular blocks of 100 meters long, 100 meters wide, and 5 meters tall. The blocks interlock on top and bottom (like Legos), and they cannot be stacked sideways. Using special lifters, putting stacks of blocks at the same height on ground or on top of another set of equal-height stacks takes one week regardless of how tall the stacks are or how many stacks are lifted. The prefabrication time of the blocks doesn’t count since they are already in stock. No resource/budget limitations (i.e., you can have as many stacks as possible at the same time),

36 Algorithms of Skyscrapers Project
Problem Part A: If a client wants to build a 100-meter long, 100-meter wide, and 1250-meter high tower as quickly as possible, what is the shortest amount of time that it will take to build the tower? Show your algorithm in both flowchart and pseudocode forms. Problem Part B: Develop a general algorithm for skyscrapers of 100-meter long, 100-meter wide, and N-meter high (where N is a multiple of 5) in pseudocode format.

37 Review of Pseudocode

38 Convention of Pseudocode
Write pseudocode for: calculating total number of blocks needed for N-meter high skyscraper. calculating the remainder of number of stacks divided by 2. creating a while loop to work as long as the number of stacks is not equal to 1. creating a counter to increment the week count in a while loop.

39 Convention of Pseudocode
Write pseudocode for: calculating total number of blocks needed for N-meter high skyscraper. numberBlock = N/5

40 Convention of Pseudocode
Write pseudocode for: calculating the remainder of number of stacks divided by 2. Remainder = numberStack % 2

41 Convention of Pseudocode
Write pseudocode for: creating a while loop to work as long as the number of stacks is not equal to 1. While loop numberStack ≠ 1 …… end-loop

42 Convention of Pseudocode
Write pseudocode for: creating a counter to increment the week count in a while loop. weekCounter = 0 While loop numberStack ≠ 1 weekCounter = weekCounter + 1 end-loop

43 Skyscraper Algorithms
Group Presentation of Skyscraper Algorithms

44 Decimal-to-Binary Conversion Algorithm

45 Decimal-to-Binary Conversion
2 2 4 0 Decimal: Binary: No. of Division No. of One’s: No. of Weeks: = 11 2 1 2 0 2 6 0 2 3 0 2 1 5 1 2 7 1 2 3 1 1

46 Programming: A Crash Course of C

47 C Example: Sum of 1+ 2+…+N // Calculate the Sum of 1 + 2 + 3 + ….. + N
#include <stdio.h> int main () { int n, i; int sum = 0; printf("Enter N: "); scanf("%d", &n); for (i = 1; i <= n; i++) sum = sum + i; printf("Sum = %d\n", sum); return 0; } //: all text contained in a /* and */ (in C) or after // (in C++) are comments. #include directive: It allows external header files to be processed by the compiler. int main(): When you do not require access to the command line arguments. The return type of main() must always be an int, this allows a return code to be passed to the invoker. stdio.h: The header defines three variable types, several macros, and various functions for performing input and output. Int: Basic signed integer data type, stored as 4 bytes. printf(): Sends formatted output to stdout (screen or command line). scanf(): Reads formatted input from stdin (screen or command line). %d: %d is the format specifier for an integer value ( int variable) \n: Line feed or new line. &: Returns the address of a variable. ++: Increment operator increases the integer value by one. for: A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. for ( init; condition; increment ) { statement(s); } return: Terminates current function and returns specified value to the caller function

48 C Example: Average of Numbers
// Calculate the average of three numbers // average = (a + b + c)/3 #include <stdio.h> int main() { float a, b, c; float average; printf ("Averaging three numbers \n"); printf ("Enter three numbers a, b, and c: "); scanf ("%f %f %f", &a, &b, &c); average = (a + b + c)/3.0; printf("Average = %.2f\n", average); return 0; } float: Real floating-point type, stored as 4 bytes. %f: %f stands for float format specifier. %.2f: print as a floating point with a precision of 2 digits after the decimal point. Arithmetic operators: +, -, *, /, %, ++, --.

49 C Example: Linear Equation
// Solve Linear Equation // ax + b = c, x = (c - b)/a #include <stdio.h> int main() { float a, b, c; float x; printf("Solve linear equation: ax + b = c\n"); printf("Enter coefficients: a, b, c: "); scanf ("%f %f %f", &a, &b, &c); x = (c - b)/a; printf ("x = %.2f\n", x); return 0; }

50 C Example: Skyscraper Algorithm
#include <stdio.h> int main() { int noWeek, buildingHeight, noStack, remainder; noWeek = 1; printf ("Hello! Please enter the building height: "); scanf ("%d", &buildingHeight); noStack = buildingHeight/5; while (noStack != 1) remainder = noStack%2; noStack = (noStack-remainder)/2; noWeek = noWeek + remainder + 1; } printf("Number of Week to Build the Skyscraper is: %d\n", noWeek); return 0; Logical operators: ==, !=, >, <, >=, <=. while loop: A while loop in C programming repeatedly executes a target statement as long as a given condition is true. while(condition) { statement(s); }

51 C Example: Square Root #include <stdio.h>
#include <math.h> int main() { float a; float x; printf("Please enter the number: "); scanf("%f", &a); if (a < 0) printf("No solution.\n"); else x = sqrt(a); printf("sqrt(%.2f) = %.5f\n", a, x); } return 0; math.h: The math.h header defines various mathematical functions. sqrt(): sqrt computes square root. if: An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions. if (condition is true) { statements } else if (condition is true) else

52 C Example: Integer Array
#include <stdio.h> #define MAX 5 int main() { int array[MAX]; float sum = 0.; int i; printf("Enter 5 integers: "); for (i =0; i < MAX; i++) scanf("%d", &array[i]); sum = sum + array[i]; } printf("array[%d] = %d\n", i, array[i]); printf("Average = %.2f\n", sum/MAX); return 0; #define: The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file. array[MAX]: Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. You declare only one array variable, and specific element in an array is accessed by an index. type arrayName [ arraySize ];

53 C Example: Integer Array
Output: Enter 5 integers: array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 5 Average = 3.00 Output: Enter 5 integers: array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 6 Average = 3.20

54 C Example: Character Strings
// Strings are Array of Characters. #include <stdio.h> #include <string.h> #define MAX_STRING_LENGTH 80 int main() { char str[MAX_STRING_LENGTH]; unsigned long length; int i; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '!'; str[6] = '\0'; length = strlen(str); for (i = 0; i < length; i++) printf("str[%d] = %c\n", i, str[i]); printf("\nstring =\t%s\n", str); printf("length =\t%lu\n", length); return 0; }

55 C Example: Character Strings
// Strings are Array of Characters. #include <stdio.h> #include <string.h> #define MAX_STRING_LENGTH 80 int main() { char str[MAX_STRING_LENGTH]; unsigned long length; int i; str[0] = 'H'; str[1] = 'e'; str[2] = 'l'; str[3] = 'l'; str[4] = 'o'; str[5] = '!'; str[6] = '\0'; length = strlen(str); for (i = 0; i < length; i++) printf("str[%d] = %c\n", i, str[i]); printf("\nstring =\t%s\n", str); printf("length =\t%lu\n", length); return 0; } Output: str[0] = H str[1] = e str[2] = l str[3] = l str[4] = o str[5] = ! string = Hello! length = 6

56 C Example: Strings Operations
// Strings IO from Command Line // String Comparison, Concatenation & Copy #include <stdio.h> #include <string.h> #define MAX_STRING_LENGTH 80 int main() { char str1[MAX_STRING_LENGTH]; char str2[MAX_STRING_LENGTH]; char str3[MAX_STRING_LENGTH]; printf("\nString 1: "); scanf("%s", str1); printf("\nString 2: "); scanf("%s", str2); printf("\nString1 =\t%s\n", str1); printf("\nString2 =\t%s\n", str2); if(strcmp(str1, str2) > 0) { printf("\nString1 > String2\n"); strcat(str1, str2); printf("\nString1=\t%s\n", str1); printf("\nString2=\t%s\n", str2); } else if (strcmp(str1, str2) < 0) printf("\nString1 < String2\n"); strcat(str2, str1); else printf("\nString1 = String2\n"); strcpy(str3, str1); printf("\nString3: %s\n", str3); return 0;

57 ASCII Code

58 C Example: Strings Operations
Output: String 1: Ally String 2: Henry String1 = Ally String2 = Henry String1 < String2 String1= Ally String2= HenryAlly Output: String 1: Alexia String 2: Zoe String1 = Alexia String2 = Zoe String1 < String2 String1= Alexia String2= ZoeAlexi Output: String 1: ELRO String 2: ELRO String1 = ELRO String2 = ELRO String1 = String2 String3: ELRO

59 C Example: File R/W, Strings & Array
// Read / Write Strings and Integers from / to Files #include <stdio.h> #define FILESIZE 10 #define STRINGLENGTH 15 int main() { FILE* fileInput = NULL; FILE* fileOutput = NULL; char str[FILESIZE][STRINGLENGTH]; int number[FILESIZE]; int i; fileInput = fopen("input.txt", "r"); fileOutput = fopen("output.txt", "w"); for (i = 0; i < FILESIZE; i++) fscanf (fileInput, "%s %d", str[i], &number[i]); fprintf(fileOutput, "string[%d] = %13s number[%d] = %3d\n\n", i, str[i], i, number[i]*2); fprintf(fileOutput, "%s ", str[i]); fprintf(fileOutput, "\n\n"); fclose(fileInput); fclose(fileOutput); }

60 C Example: File R/W, Strings & Array
In Xcode, after copying and pasting the program, follow the following steps: Drag and drop the input files into the project folder Set Working Directory through: Product > Scheme > Edit Scheme > Working Directory Build and then run the current scheme Display the output file through: Control Click Project folder > Add Files to “project folder”……

61 C Example: File R/W, Strings & Array
FILE: in.txt The 10 purpose 20 of 30 this 40 project 50 is 60 to 70 have 80 fun 90 :) 100 FILE: output.txt string[0] = The number[0] = 20 string[1] = purpose number[1] = 40 string[2] = of number[2] = 60 string[3] = this number[3] = 80 string[4] = project number[4] = 100 string[5] = is number[5] = 120 string[6] = to number[6] = 140 string[7] = have number[7] = 160 string[8] = fun number[8] = 180 string[9] = :) number[9] = 200 The purpose of this project is to have fun :)

62 C Example: File R/W, Strings & Array
FILE: input.txt ELRO 1 Computational 2 Service 3 Company 4 is 5 based 6 in 7 New 8 York 9 City. 10 FILE: output.txt string[0] = ELRO number[0] = 2 string[1] = Computational number[1] = 4 string[2] = Service number[2] = 6 string[3] = Company number[3] = 8 string[4] = is number[4] = 10 string[5] = based number[5] = 12 string[6] = in number[6] = 14 string[7] = New number[7] = 16 string[8] = York number[8] = 18 string[9] = City number[9] = 20 ELRO Computational Service Company is based in New York City.

63 Sorting Algorithms and Implementations

64 Sorting Algorithms Selection Sort I Bubble Sort Selection Sort 2
Insertion Sort

65 Sort Main Functions // This is the main function which can call different sort functions #include <stdio.h> int main(int argc, const char * argv[]) { int i, number; int a[20]; printf("Number of integers: "); scanf("%d", &number); printf("Enter %d integers: ", number); for (i = 0; i< number; i++) scanf("%d", &a[i]); sort(a, number); printf("%d ", a[i]); printf("\n"); return 0; }

66 Selection Sort I Selection Sort I compares the element in the first position with the elements in the rest of the array in order. Swap them if the first one is greater than any other element in the array, and result in the smallest element in the first position. Find the second smallest element through the same procedure. Continue until the array is sorted

67 Selection Sort I Example
3 5 1 2 4

68 Selection Sort I Code // Selection Sort: Compare the elements with the elements in the rest of the // array in order. Swap them until the whole array is sorted. void SelectionSort (int a[], int array_size) { int i, j, temp; for (i = 0; i < array_size-1; i++) for (j = i+1; j < array_size; j++) if (a[i] > a[j]) temp = a[i]; a[i] = a[j]; a[j] = temp; } 3 5 1 2 4

69 Selection Sort II It basically determines the minimum (or maximum) of the list and swaps it with the element at the index where its supposed to be. Find the smallest element in the array. Exchange it with the element in the first position. Find the second smallest element and exchange it with the element in the second position. Continue until the array is sorted.

70 Selection Sort II Example
3 5 1 2 4

71 Selection Sort II Code // Selection Sort: It basically determines the minimum (or maximum) of the list and // swaps it with the element at the index where its supposed to be. void SelectionSort (int a[], int array_size) { int i; int j, min, temp; for (i = 0; i < array_size - 1; i++) min = i; for (j = i+1; j < array_size; j++) if (a[j] < a[min]) min = j; } temp = a[i]; a[i] = a[min]; a[min] = temp; 3 5 1 2 4

72 Bubble Sort Bubble Sort works by comparing each element of the list with the element next to it and swapping them if required. When we compare pairs of adjacent elements and none are out of order, the list is sorted. If any are out of order, we must have to swap them to get an ordered list. Bubble sort will make passes though the list swapping any adjacent elements that are out of order.

73 Bubble Sort 3 5 1 2 4

74 Bubble Sort Code // Bubble Sort: comparing each element of the list with the element // next to it and swapping them if required. void BubbleSort (int a[], int array_size) { int i, j, temp; for (i = 0; i < (array_size - 1); ++i) for (j = 0; j < array_size i; ++j ) if (a[j] > a[j+1]) temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } 3 5 1 2 4

75 Insertion Sort Insertion Sort starts from the beginning, traverses through the list and as you find elements misplaced by precedence you remove them and insert them back into the right position. Eventually what you have is a sorted list of elements. Adding a new element to a sorted list will keep the list sorted if the element is inserted in the correct place. A single element list is sorted. Inserting a second element in the proper place keeps the list sorted. This is repeated until all the elements have been inserted into the sorted part of the list.

76 Insertion Sort 3 5 1 2 4

77 Insertion Sort Code // Insertion Sort: You start from the beginning, traverse through the list // and as you find elements misplaced by precedence you remove them // and insert them back into the right position. void insertionSort (int a[], int array_size) { int i, j, key; for (i = 1; i < array_size; i++) key = a[i]; for (j = i; j > 0 && a[j-1] > key; j--) a[j] = a[j-1]; a[j] = key; } 3 5 1 2 4

78 Sort Main Functions - Strings
// This is the main function which can call different sort functions #include <stdio.h> #include <string.h> #define STRINGLENGTH 15 int main(int argc, const char * argv[]) { int i, number; char str[20][STRINGLENGTH]; printf("Number of strings: "); scanf("%d", &number); printf("Enter %d strings: ", number); for (i = 0; i< number; i++) scanf("%s", str[i]); SortStr(str, number); printf("%s ", str[i]); printf("\n"); return 0; }

79 Selection Sort I Code - Strings
// Selection Sort: Compare the elements with the elements in the rest of the // array in order. Swap them until the whole array is sorted. void SelectionSort (char str[][STRINGLENGTH], int array_size) { int i, j; char temp[STRINGLENGTH]; for (i = 0; i < array_size-1; i++) for (j = i+1; j < array_size; j++) if (strcmp(str[i], str[j]) > 0) strcpy(temp, str[i]); strcpy(str[i], str[j]); strcpy(str[j], temp); }

80 Searching Algorithms and Implementations

81 Searching Algorithms Linear Search Binary Search

82 Search Functions // This is the main function which can call different search functions #include <stdio.h> int main() { int i, number, key; int a[20]; printf("Number of integers: "); scanf("%d", &number); printf("Enter %d integers: ", number); for (i = 0; i< number; i++) scanf("%d", &a[i]); printf("The array of integers:\n"); printf("%d ", a[i]); printf("\n"); printf("Enter your search key: "); scanf("%d", &key); search (key, a, number); return 0; }

83 Linear Search Linear Search is the simplest searching algorithm.
It uses a loop to sequentially step through an array, starting with the first element. It compares each element with the value being searched for and stops when that value is found or the end of the array is reached.

84 Linear Search Code // Linear Search
int LinearSearch (int key, int a[], int array_size) { int i, found = 0; for(i = 0; i < array_size; i++) if (a[i] == key) found = 1; printf ("%2d] %2d\n\n", i, a[i]); } if (found == 1) return 1; else printf ("Can not find %d\n", key); return -1;

85 Binary Search Binary search is much more efficient than the linear search. It requires the list to be in order. The algorithm starts searching with the middle element. If the item is less than the middle element, it starts over searching the first half of the list. If the item is greater than the middle element, the search starts over starting with the middle element in the second half of the list. It then continues halving the list until the item is found.

86 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo hi

87 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo mid hi

88 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo hi

89 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo mid hi

90 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo hi

91 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo mid hi

92 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo hi

93 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo hi mid

94 Binary Search Binary search. Given value and sorted array a[], find index i such that a[i] = value, or report that no such index exists. Invariant. Algorithm maintains a[lo]  value  a[hi]. Ex. Binary search for 33. 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97 1 2 3 4 5 6 7 8 9 10 11 12 13 14 lo hi mid

95 Binary Search Code // Binary Search:
int binsearch(int x, int v[], int n) { int low,high,mid; low = 0; high = n - 1; while(low<=high) mid = (low + high) / 2; if(x < v[mid]) high = mid + 1; } else if(x > v[mid]) low = mid + 1; else return mid; return -1;

96 Comparison of Algorithm Complexity
Linear Search Looks through an array serially, one element at a time. The time taken to search the list increases as the list grows. Its time complexity is an O(n). Binary Search Start with the middle of a sorted array, and jump to the half way through the subarray, and compare again etc. Its time complexity is an O(log n). * n is the size of the searched array.

97 Comparison of Algorithm Complexity
Build a skyscraper of 1280 m (256 blocks): Brute-Force Skyscraper Algorithm Build a skyscraper block by block. It will take 256 weeks. Its time complexity is an O(n). Divide-by-2 Skyscraper Algorithm Start with 256 blocks on ground. Stack half of them on top of another half, and continue doing so until finishing. It will take log weeks. Its time complexity is an O(log n). * n is the number of the blocks.

98 Algorithm Time Complexity
The time complexity of an algorithm is the amount of time taken by an algorithm to run as a function of the number of elements representing the input. The time complexity of an algorithm is commonly expressed using big O notation, O(), which excludes coefficients and lower order terms. For example, O(1) is constant time O(n) is linear time O(log n) is logarithmic time O(nk) is polynomial time

99 Algorithms and Programming
Types of Algorithms Brute-Force (or Exhaustive Search) Divide and Conquer The Greedy Method Recursion Algorithms of Skyscrapers Project Review of Pseudo Code Decimal-to-Binary Conversion Algorithm Programming: A Crash Course of C Sorting Algorithms and Implementations Searching Algorithms and Implementations

100 Q & A


Download ppt "Algorithms and Programming"

Similar presentations


Ads by Google