Matakuliah Tahun Versi : T0016/Algoritma dan Pemrograman : 2005 : versi 2 Pertemuan 24 Teknik Searching 1 Learning Outcomes Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : • Menjelaskan berbagai teknik searching 2 Outline Materi • Sequential search • Binary Search • Interpolation search 3 Sequential Search In computer science, linear search is a search algorithm , also known as sequential search, that is suitable for searching a set of data for a particular value. 4 Linear search public int sequentialSearch(int arr[], int key) { for (int k = 0; k < arr.length; k++) if (arr[k] == key) return k; return -1; // Failure } // sequentialSearch() 5 Binary Search • Binary Search will search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. • If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. 6 • Finding the middle is often coded as mid = (high + low)/2; • This overflows if high and low are close to the largest expressible integer. The following gives the same result and never overflows, if high and low are non-negative. mid = low + (high - low)/2; 7 Algoritma Binary Search function binarySearch(a, value, left, right) while left ≤ right mid := floor((left+right)/2) if a[mid] = value return mid if value < a[mid] right := mid-1 else if value > a[mid] left := mid+1 return not found 8 Interpolation Search • An approximate location is interpolated from the first and last items of a sorted array, then a linear search finds the actual location. 9 Interpolation Search function search( key : typekey; var r : dataarray ) : integer; var high, j, low : integer; begin low := 1; high := n; while (r[high].k >= key) and (key > r[low].k) do begin j := trunc( (key-r[low].k) / (r[high].k-r[low].k) * (high-low) ) + low; if key > r[j].k then low := j+1 else if key < r[j].k then high := j-1 else low := j end; if r[low].k = key then search := low {*** found(r[low]) ***} else search := -1; {*** notfound(key) ***} end; 10 Penutup • Linear search merupakan algoritma pencarian yang sangat mudah, namun menjadi sangat lama jika datanya sangat banyak. 11