Pertemuan 24 Teknik Searching Matakuliah : T0016/Algoritma dan Pemrograman Tahun : 2005 Versi : versi 2 Pertemuan 24 Teknik Searching
Menjelaskan berbagai teknik searching Learning Outcomes Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : Menjelaskan berbagai teknik searching
Outline Materi Sequential search Binary Search Interpolation search
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.
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()
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.
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;
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
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.
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;
Penutup Linear search merupakan algoritma pencarian yang sangat mudah, namun menjadi sangat lama jika datanya sangat banyak.