logo

Programa C para buscar un elemento en una matriz

En este artículo discutiremos el programa C para buscar un elemento en un Array con sus diferentes formas y ejemplos.

¿Qué es una matriz?

A estructura de datos llamado un formación contiene una serie de longitud fija de elementos del mismo tipo. Se utiliza con frecuencia para almacenar y manipular colecciones de datos porque la indexación permite un acceso eficiente.

lenguaje maravilloso

Ej: números enteros[] = {10, 20, 30, 40, 50};

Buscar un elemento en una matriz

Una operación típica en programación de computadoras es buscar un elemento particular en una matriz. La eficiencia de su código se puede mejorar enormemente mediante el uso de algoritmos de búsqueda eficientes, ya sea que esté buscando la existencia de un determinado valor ubicando el índice de un elemento o verificando si un elemento existe. En este artículo se analizarán los numerosos métodos para buscar elementos en una matriz utilizando el lenguaje de programación C.

Existen principalmente dos formas de buscar un elemento en una matriz:

1. Búsqueda lineal

Una estrategia de búsqueda sencilla que se utiliza para localizar un elemento determinado en una matriz o lista se llama búsqueda lineal , a veces denominado búsqueda secuencial . Opera comparando cada miembro de la matriz con el valor objetivo para encontrar un fósforo o atravesar la matriz completa de forma iterativa.

agregar a la matriz java

Los pasos fundamentales en la búsqueda lineal son los siguientes:

    Comenzar con los elementos superiores de la matriz.
  1. El valor objetivo debe compararse con el elemento actual.
  2. La búsqueda tiene éxito si el elemento actual coincide con el valor solicitado y luego el algoritmo puede devolver el índice del elemento o cualquier otro resultado deseado.
  3. Vaya al siguiente elemento de la matriz si el elemento actual no coincide con el valor deseado.
  4. Hasta que se logre una coincidencia o se llegue al final de la matriz, repita los pasos 2 a 4.

Programa:

 #include int linearSearch(int arr[], int n, int target) { for (int i = 0; i<n; i++) { if (arr[i]="=" target) return i; the index target is found } -1; -1 not int main() arr[]="{5," 2, 8, 12, 3}; n="sizeof(arr)" sizeof(arr[0]); calculate number of elements in array result="linearSearch(arr," n, target); (result="=" -1) printf('element found
'); else at %d
', result); 0; < pre> <p> <strong>Output:</strong> </p> <pre> An element found at index 2 </pre> <h3>2. Binary Search</h3> <p>The <strong> <em>binary search</em> </strong> technique is utilized to quickly locate a specific element in a sorted <strong> <em>array</em> </strong> or <strong> <em>list</em> </strong> . It uses a <strong> <em>divide-and-conquer</em> </strong> <strong> <em>strategy</em> </strong> , periodically cutting the search area in half until the target element is located or found to be absent.</p> <p>This is how binary search functions:</p> <ol class="points"> <li>Have a sorted array or list as a base.</li> <li>Establish two pointers, <strong> <em>left</em> </strong> and <strong> <em>right</em> </strong> , with their initial values pointing to the array&apos;s first and end members.</li> <li>Use <strong> <em>(left + right) / 2</em> </strong> to get the index of the center element.</li> <li>Compare the target value to the middle element. <ol class="pointsa"> <li>The search is successful if they are equal, and then the program can return the <strong> <em>index</em> </strong> or any other required result.</li> <li>The right pointer should be moved to the element preceding the <strong> <em>middle element</em> </strong> if the middle element is greater than the target value.</li> <li>Move the <strong> <em>left pointer</em> </strong> to the element following the <strong> <em>middle element</em> </strong> if the middle element&apos;s value is less than the target value.</li> </ol></li> <li>Steps <strong> <em>3</em> </strong> and <strong> <em>4</em> </strong> should be repeated until the target element is located or the left pointer exceeds the right pointer.</li> <li>The desired element is not in the array if it cannot be located.</li> </ol> <p> <strong>Program:</strong> </p> <pre> #include int binarySearch(int arr[], int left, int right, int target) { while (left <= right) { int mid="left" + (right-left) 2; if (arr[mid]="=" target) return mid; the index target is found } < left="mid" 1; else right="mid-1;" -1; -1 not main() arr[]="{2," 5, 8, 12, 20, 23, 28}; n="sizeof(arr)" sizeof(arr[0]); calculate number of elements in array result="binarySearch(arr," 0, - 1, target); (result="=" -1) printf('element found
'); at %d
', result); 0; pre> <p> <strong>Output:</strong> </p> <pre> An element found at index 4 </pre> <hr></=></pre></n;>

2. Búsqueda binaria

El búsqueda binaria La técnica se utiliza para localizar rápidamente un elemento específico en un orden. formación o lista . Utiliza un divide y conquistaras estrategia , cortando periódicamente el área de búsqueda a la mitad hasta que se localice o se descubra que el elemento objetivo está ausente.

Así es como funciona la búsqueda binaria:

  1. Tenga una matriz o lista ordenada como base.
  2. Establecer dos indicaciones, izquierda y bien , con sus valores iniciales apuntando al primer y final miembros de la matriz.
  3. Usar (izquierda + derecha) / 2 para obtener el índice del elemento central.
  4. Compare el valor objetivo con el elemento medio.
    1. La búsqueda tiene éxito si son iguales y luego el programa puede devolver el índice o cualquier otro resultado requerido.
    2. El puntero derecho debe moverse al elemento que precede al elemento medio si el elemento medio es mayor que el valor objetivo.
    3. Mueve el puntero izquierdo al elemento que sigue a la elemento medio si el valor del elemento intermedio es menor que el valor objetivo.
  5. Pasos 3 y 4 debe repetirse hasta que se ubique el elemento de destino o el puntero izquierdo exceda el puntero derecho.
  6. El elemento deseado no está en la matriz si no se puede ubicar.

Programa:

 #include int binarySearch(int arr[], int left, int right, int target) { while (left <= right) { int mid="left" + (right-left) 2; if (arr[mid]="=" target) return mid; the index target is found } < left="mid" 1; else right="mid-1;" -1; -1 not main() arr[]="{2," 5, 8, 12, 20, 23, 28}; n="sizeof(arr)" sizeof(arr[0]); calculate number of elements in array result="binarySearch(arr," 0, - 1, target); (result="=" -1) printf(\'element found
\'); at %d
\', result); 0; pre> <p> <strong>Output:</strong> </p> <pre> An element found at index 4 </pre> <hr></=>