Dada una array ordenada de n valores uniformemente distribuidos arr[], escriba una función para buscar un elemento x en particular en la array.
La búsqueda lineal encuentra el elemento en el tiempo O(n), la búsqueda por salto toma el tiempo O(√ n) y la búsqueda binaria toma el tiempo O(log n).
La búsqueda de interpolación es una mejora con respecto a la búsqueda binariapor ejemplo, donde los valores en una array ordenada se distribuyen uniformemente. La interpolación construye nuevos puntos de datos dentro del rango de un conjunto discreto de puntos de datos conocidos. La búsqueda binaria siempre va al elemento central para verificar. Por otro lado, la búsqueda por interpolación puede ir a diferentes ubicaciones según el valor de la clave que se busca. Por ejemplo, si el valor de la clave está más cerca del último elemento, es probable que la búsqueda por interpolación comience la búsqueda hacia el lado final.
Para encontrar la posición a buscar, utiliza la siguiente fórmula.
// The idea of formula is to return higher value of pos // when element to be searched is closer to arr[hi]. And // smaller value when closer to arr[lo] arr[] ==> Array where elements need to be searched x ==> Element to be searched lo ==> Starting index in arr[] hi ==> Ending index in arr[]
Hay muchos métodos de interpolación diferentes y uno de ellos se conoce como interpolación lineal. La interpolación lineal toma dos puntos de datos que asumimos como (x1,y1) y (x2,y2) y la fórmula es: en el punto (x,y).
Este algoritmo funciona de la misma manera que buscamos una palabra en un diccionario. El algoritmo de búsqueda por interpolación mejora el algoritmo de búsqueda binaria. La fórmula para encontrar un valor es: K = datos-bajo/alto-bajo.
K es una constante que se utiliza para reducir el espacio de búsqueda. En el caso de búsqueda binaria, el valor de esta constante es: K=(bajo+alto)/2.
La fórmula para pos se puede derivar de la siguiente manera.
Let's assume that the elements of the array are linearly distributed. General equation of line : y = m*x + c. y is the value in the array and x is its index. Now putting value of lo,hi and x in the equation arr[hi] = m*hi+c ----(1) arr[lo] = m*lo+c ----(2) x = m*pos + c ----(3) m = (arr[hi] - arr[lo] )/ (hi - lo) subtracting eqxn (2) from (3) x - arr[lo] = m * (pos - lo) lo + (x - arr[lo])/m = pos pos = lo + (x - arr[lo]) *(hi - lo)/(arr[hi] - arr[lo])
Algoritmo
El resto del algoritmo de interpolación es el mismo excepto por la lógica de partición anterior.
Paso 1: en un ciclo, calcule el valor de «pos» utilizando la fórmula de posición de la sonda.
Paso 2: si es una coincidencia, devuelva el índice del elemento y salga.
Paso 3: si el elemento es menor que arr[pos], calcule la posición de la sonda del subarreglo izquierdo. De lo contrario, calcule lo mismo en el subarreglo derecho.
Paso 4: repita hasta que se encuentre una coincidencia o el subarreglo se reduzca a cero.
A continuación se muestra la implementación del algoritmo.
C++
// C++ program to implement interpolation search #include<bits/stdc++.h> using namespace std; // If x is present in arr[0..n-1], then returns // index of it, else returns -1. int interpolationSearch(int arr[], int n, int x) { // Find indexes of two corners int lo = 0, hi = (n - 1); // Since array is sorted, an element present // in array must be in range defined by corner while (lo <= hi && x >= arr[lo] && x <= arr[hi]) { if (lo == hi) { if (arr[lo] == x) return lo; return -1; } // Probing the position with keeping // uniform distribution in mind. int pos = lo + (((double)(hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); // Condition of target found if (arr[pos] == x) return pos; // If x is larger, x is in upper part if (arr[pos] < x) lo = pos + 1; // If x is smaller, x is in the lower part else hi = pos - 1; } return -1; } // Driver Code int main() { // Array of items on which search will // be conducted. int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47}; int n = sizeof(arr)/sizeof(arr[0]); int x = 18; // Element to be searched int index = interpolationSearch(arr, n, x); // If element was found if (index != -1) cout << "Element found at index " << index; else cout << "Element not found."; return 0; } // This code is contributed by Mukul Singh.
C++
// C++ program to implement interpolation // search with recursion #include <bits/stdc++.h> using namespace std; // If x is present in arr[0..n-1], then returns // index of it, else returns -1. int interpolationSearch(int arr[], int lo, int hi, int x) { int pos; // Since array is sorted, an element present // in array must be in range defined by corner if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { // Probing the position with keeping // uniform distribution in mind. pos = lo + (((double)(hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); // Condition of target found if (arr[pos] == x) return pos; // If x is larger, x is in right sub array if (arr[pos] < x) return interpolationSearch(arr, pos + 1, hi, x); // If x is smaller, x is in left sub array if (arr[pos] > x) return interpolationSearch(arr, lo, pos - 1, x); } return -1; } // Driver Code int main() { // Array of items on which search will // be conducted. int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 }; int n = sizeof(arr) / sizeof(arr[0]); // Element to be searched int x = 18; int index = interpolationSearch(arr, 0, n - 1, x); // If element was found if (index != -1) cout << "Element found at index " << index; else cout << "Element not found."; return 0; } // This code is contributed by equbalzeeshan
C
// C program to implement interpolation search // with recursion #include <stdio.h> // If x is present in arr[0..n-1], then returns // index of it, else returns -1. int interpolationSearch(int arr[], int lo, int hi, int x) { int pos; // Since array is sorted, an element present // in array must be in range defined by corner if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { // Probing the position with keeping // uniform distribution in mind. pos = lo + (((double)(hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); // Condition of target found if (arr[pos] == x) return pos; // If x is larger, x is in right sub array if (arr[pos] < x) return interpolationSearch(arr, pos + 1, hi, x); // If x is smaller, x is in left sub array if (arr[pos] > x) return interpolationSearch(arr, lo, pos - 1, x); } return -1; } // Driver Code int main() { // Array of items on which search will // be conducted. int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 18; // Element to be searched int index = interpolationSearch(arr, 0, n - 1, x); // If element was found if (index != -1) printf("Element found at index %d", index); else printf("Element not found."); return 0; }
Java
// Java program to implement interpolation // search with recursion import java.util.*; class GFG { // If x is present in arr[0..n-1], then returns // index of it, else returns -1. public static int interpolationSearch(int arr[], int lo, int hi, int x) { int pos; // Since array is sorted, an element // present in array must be in range // defined by corner if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { // Probing the position with keeping // uniform distribution in mind. pos = lo + (((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); // Condition of target found if (arr[pos] == x) return pos; // If x is larger, x is in right sub array if (arr[pos] < x) return interpolationSearch(arr, pos + 1, hi, x); // If x is smaller, x is in left sub array if (arr[pos] > x) return interpolationSearch(arr, lo, pos - 1, x); } return -1; } // Driver Code public static void main(String[] args) { // Array of items on which search will // be conducted. int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 }; int n = arr.length; // Element to be searched int x = 18; int index = interpolationSearch(arr, 0, n - 1, x); // If element was found if (index != -1) System.out.println("Element found at index " + index); else System.out.println("Element not found."); } } // This code is contributed by equbalzeeshan
Python3
# Python3 program to implement # interpolation search # with recursion # If x is present in arr[0..n-1], then # returns index of it, else returns -1. def interpolationSearch(arr, lo, hi, x): # Since array is sorted, an element present # in array must be in range defined by corner if (lo <= hi and x >= arr[lo] and x <= arr[hi]): # Probing the position with keeping # uniform distribution in mind. pos = lo + ((hi - lo) // (arr[hi] - arr[lo]) * (x - arr[lo])) # Condition of target found if arr[pos] == x: return pos # If x is larger, x is in right subarray if arr[pos] < x: return interpolationSearch(arr, pos + 1, hi, x) # If x is smaller, x is in left subarray if arr[pos] > x: return interpolationSearch(arr, lo, pos - 1, x) return -1 # Driver code # Array of items in which # search will be conducted arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47] n = len(arr) # Element to be searched x = 18 index = interpolationSearch(arr, 0, n - 1, x) if index != -1: print("Element found at index", index) else: print("Element not found") # This code is contributed by Hardik Jain
C#
// C# program to implement // interpolation search using System; class GFG{ // If x is present in // arr[0..n-1], then // returns index of it, // else returns -1. static int interpolationSearch(int []arr, int lo, int hi, int x) { int pos; // Since array is sorted, an element // present in array must be in range // defined by corner if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { // Probing the position // with keeping uniform // distribution in mind. pos = lo + (((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); // Condition of // target found if(arr[pos] == x) return pos; // If x is larger, x is in right sub array if(arr[pos] < x) return interpolationSearch(arr, pos + 1, hi, x); // If x is smaller, x is in left sub array if(arr[pos] > x) return interpolationSearch(arr, lo, pos - 1, x); } return -1; } // Driver Code public static void Main() { // Array of items on which search will // be conducted. int []arr = new int[]{ 10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47 }; // Element to be searched int x = 18; int n = arr.Length; int index = interpolationSearch(arr, 0, n - 1, x); // If element was found if (index != -1) Console.WriteLine("Element found at index " + index); else Console.WriteLine("Element not found."); } } // This code is contributed by equbalzeeshan
Javascript
<script> // Javascript program to implement Interpolation Search // If x is present in arr[0..n-1], then returns // index of it, else returns -1. function interpolationSearch(arr, lo, hi, x){ let pos; // Since array is sorted, an element present // in array must be in range defined by corner if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { // Probing the position with keeping // uniform distribution in mind. pos = lo + Math.floor(((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo]));; // Condition of target found if (arr[pos] == x){ return pos; } // If x is larger, x is in right sub array if (arr[pos] < x){ return interpolationSearch(arr, pos + 1, hi, x); } // If x is smaller, x is in left sub array if (arr[pos] > x){ return interpolationSearch(arr, lo, pos - 1, x); } } return -1; } // Driver Code let arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47]; let n = arr.length; // Element to be searched let x = 18 let index = interpolationSearch(arr, 0, n - 1, x); // If element was found if (index != -1){ document.write(`Element found at index ${index}`) }else{ document.write("Element not found"); } // This code is contributed by _saurabh_jaiswal </script>
Element found at index 4
Echa un vistazo al curso de autoaprendizaje de DSA
Este artículo es una contribución de Aayu Sachdev . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA