C By Discovery (4th Edition)

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Intermediate Programming CSE 1320 Lecture 07 Chapter 4: 4.9-4.10 Searching 43 67 22 98 47 12 35 88 56 55 49 0 1 2 3 4 5 6 7 8 9 10 • Searching an array to find an element in the array – birthdays, – ids, – names, – sizes • Each element of the array is inspected to see if it is the desired element Linear Search • Given: – an array A of n elements – a value T to search for • Initialize i to 0 • loop while i is less than n – Compare T to the ith element in the array – If they are equal, return i. – If they are not equal, increment I • If T is not found, return -1. Algorithm • Worst case: loop is executed n times • Average case: loop is executed n/2 times Performance is O(n) “approximately” proportional to n: for large n, the number of steps in the algorithm will be less than or equal to some constant times n plus other terms that do not grow as fast as n Analysis Implementation #include <stdio.h> #define SIZE 11 int linear_search(int target, int array[], int n); int main(void) { int target, index; int array[SIZE] = {43, 67, 22, 98, 47, 12, 35, 88, 56, 55, 49}; printf(“What number? ”); scanf(“%d”, &target); index = linear_search(target, array, SIZE); if (index == -1) printf(“Not found\n”);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

Lecture07 - Searching Intermediate Programming CSE 1320...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online