logo

Algorisme de cerca binària en C

Un mètode ràpid per localitzar un element concret en una matriu ordenada és una cerca binària. La tasca inicial d'aquest algorisme és comparar el valor objectiu amb l'element central de la matriu. La cerca es considera correcta si el valor objectiu es troba a l'element central. L'algorisme buscarà a la meitat esquerra de la matriu si el valor de l'objectiu és menor que l'element central. El programa escanejarà la meitat dreta de la matriu si el valor de l'objectiu és més gran que l'element central. Aquest mètode es repeteix fins que s'esgota el valor de l'objectiu o l'interval de cerca.

Ús:

Les bases de dades, els motors de cerca i el processament de dades són només algunes de les aplicacions que utilitzen l'estratègia de cerca binària.

Característiques:

  • La matriu de valors d'entrada s'ha d'ordenar.
  • Amb cada iteració, el mètode redueix l'interval de cerca a la meitat, cosa que el fa especialment eficient per a grans conjunts de dades.
  • L'algorisme té una complexitat temporal O (log n) en el pitjor dels casos.
  • Trobar el valor desitjat el fa el programa utilitzant una estratègia de dividir i vencer.

Aquí teniu un exemple senzill de l'algorisme de cerca binària escrit en C:

 #include int binary_search(int arr[], int left, int right, int target) { while (left <= right) { int mid="left" + (right - left) 2; if (arr[mid]="=" target) return mid; } else < left="mid" 1; right="mid" -1; target not found main() arr[]="{1," 3, 5, 7, 9}; n="sizeof(arr)" sizeof(arr[0]); index="binary_search(arr," 0, 1, target); (index="=" -1) printf('target found
'); at %d
', index); 0; pre> <p> <strong>Output:</strong> </p> <pre> Target found at index 2 </pre> <ul> <li>The binary_search function accepts four arguments: the array to search, the left and right search range boundaries, and the target value to look for. The function returns its index if the desired value can be found; else, it returns -1.</li> <li>The main function creates an array arr and a value target. The binary_search function is then used to search the array for the desired value. The function returns the index where the target value was located if it was, the function returns the index at which it was found. Otherwise, the message &apos;Target not found&apos; is displayed.</li> <li>The binary search algorithm&apos;s implementation is basic. We begin by setting the left border to the array&apos;s initial index and the right boundary to the array&apos;s last index. Once the left boundary is less than or equal to the right border, the array is looped through one more time. We use the formula (left + right) / 2 within the loop to calculate the middle index of the search range. This formula computes the integer value of the middle index&apos;s floor.</li> <li>The centre member of the array is contrasted with the target value. We return the index of the middle element if they are equal. We change the right boundary to be one less than the middle index if the desired value is less than the middle element. If not, we adjust the left border so that it is one more than the centre index. We continue doing this until the goal value is obtained or the search space is filled.</li> <li>The temporal complexity of the binary search algorithm, where n is the array size, is O(log n). This is far more efficient than linear search, which has a temporal complexity of O(n), where n is the size of the array.</li> <li>Finally, the binary search technique offers a useful way to locate a particular member in a sorted array. It is easy to build and has an O(log n) time complexity, making it an efficient approach for large datasets.</li> </ul> <h3>Advantages:</h3> <ul> <li>For large datasets, the binary search algorithm is exceptionally efficient, and it is capable of handling a wide range of input sizes.</li> <li>The algorithm is simple to implement in almost all programming languages.</li> </ul> <h3>Disadvantages:</h3> <ul> <li>Before using the binary search technique, the input array must be sorted, which takes more time and memory.</li> <li>The algorithm cannot be applied to unsorted arrays.</li> <li>The algorithm may yield inaccurate results if the input array is not sorted.</li> <li>The binary search algorithm is not appropriate for tiny datasets since the technique&apos;s overhead may outweigh its benefits.</li> </ul> <h2>Conclusion:</h2> <p>A sorted array can be quickly searched for a specific element using the binary search technique. It employs a divide-and-conquer strategy to cut the search range in half with each iteration, allowing it to be highly efficient for large datasets. However, before using the binary search technique, the input array must be sorted, which takes extra time and memory. The binary search algorithm is a sophisticated data processing tool that is widely utilised in various sectors.</p> <hr></=>
  • La funció binary_search accepta quatre arguments: la matriu a cercar, els límits de l'interval de cerca esquerre i dret i el valor objectiu a cercar. La funció retorna el seu índex si es pot trobar el valor desitjat; en cas contrari, retorna -1.
  • La funció principal crea una matriu arr i un valor objectiu. Aleshores s'utilitza la funció binary_search per cercar a la matriu el valor desitjat. La funció retorna l'índex on es trobava el valor objectiu si ho era, la funció retorna l'índex en què s'ha trobat. En cas contrari, es mostra el missatge 'No s'ha trobat l'objectiu'.
  • La implementació de l'algorisme de cerca binària és bàsica. Comencem fixant el límit esquerre a l'índex inicial de la matriu i el límit dret a l'últim índex de la matriu. Un cop el límit esquerre és menor o igual que el límit dret, la matriu es fa en bucle una vegada més. Utilitzem la fórmula (esquerra + dreta) / 2 dins del bucle per calcular l'índex mitjà de l'interval de cerca. Aquesta fórmula calcula el valor sencer del sòl de l'índex mitjà.
  • El membre central de la matriu es contrasta amb el valor objectiu. Retornem l'índex de l'element central si són iguals. Canviem el límit dret perquè sigui un menys que l'índex central si el valor desitjat és menor que l'element central. Si no, ajustem la vora esquerra perquè sigui un més que l'índex central. Continuem fent-ho fins que s'obté el valor de l'objectiu o s'ompli l'espai de cerca.
  • La complexitat temporal de l'algorisme de cerca binària, on n és la mida de la matriu, és O(log n). Això és molt més eficient que la cerca lineal, que té una complexitat temporal de O(n), on n és la mida de la matriu.
  • Finalment, la tècnica de cerca binària ofereix una manera útil de localitzar un membre determinat en una matriu ordenada. És fàcil de construir i té una complexitat de temps O(log n), el que el converteix en un enfocament eficient per a grans conjunts de dades.

Avantatges:

  • Per a grans conjunts de dades, l'algoritme de cerca binari és excepcionalment eficient i és capaç de gestionar una àmplia gamma de mides d'entrada.
  • L'algorisme és senzill d'implementar en gairebé tots els llenguatges de programació.

Desavantatges:

  • Abans d'utilitzar la tècnica de cerca binària, s'ha d'ordenar la matriu d'entrada, la qual cosa requereix més temps i memòria.
  • L'algorisme no es pot aplicar a matrius no ordenades.
  • L'algorisme pot donar resultats inexactes si la matriu d'entrada no està ordenada.
  • L'algorisme de cerca binari no és adequat per a conjunts de dades petits, ja que la sobrecàrrega de la tècnica pot superar els seus beneficis.

Conclusió:

Una matriu ordenada es pot cercar ràpidament per a un element específic mitjançant la tècnica de cerca binària. Utilitza una estratègia de dividir i conquerir per reduir el rang de cerca a la meitat amb cada iteració, cosa que li permet ser altament eficient per a grans conjunts de dades. Tanmateix, abans d'utilitzar la tècnica de cerca binària, la matriu d'entrada s'ha d'ordenar, la qual cosa requereix més temps i memòria. L'algoritme de cerca binària és una eina de processament de dades sofisticada que s'utilitza àmpliament en diversos sectors.

llista enllaçada java