BUSQUEDA SECUENCIAL
Este método se usa para buscar un elemento de un vector, es explorar secuencialmente el vector, es decir; recorrer el vector desde el prior elemento hasta el último. Si se encuentra el elemento buscado se debe visualizar un mensaje similar a “Fin de Búsqueda” o “Elemento encontrado” y otro que diga “posición=” en caso contrario, visualizar un mensaje similar a “Elemento no existe en la Lista”.
Este tipo de búsqueda compara cada elemento del vector con el valor a encontrar hasta que este se consiga o se termine de leer el vector completo.
CÓDIGO FUENTE:
package vista;
import java.util.Scanner;
public class Principal {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int n,n1,i=0,nb,pos=0;
boolean sw=false;
Scanner teclado = new Scanner(System.in);
int n,n1,i=0,nb,pos=0;
boolean sw=false;
System.out.print("INGRESE EL TAMAÑO DEL ARREGLO");
n=teclado.nextInt();
int [] num=new int [n];
for ( i = 0; i < n; i++) {
System.out.print("");
System.out.print("EL ELEMENTO "+ (i+1) + " TIENE EL VALOR: ");
n1=teclado.nextInt();
num[i]=n1;
}
System.out.print("");
System.out.print("INGRESE EL NUMERO A BUSCAR: ");
nb=teclado.nextInt();
i=0;
while(i<num.length && sw==false){
if(num[i]==nb){
pos=i+1;
sw=true;
}
i++;
}
if(sw==true){
System.out.println("EL NUMERO FUE ENCONTRADO, ESTA EN LA POSICION: "+pos);
}
else
System.out.println("EL NUMERO NO SE ENCUENTRA");
}
n=teclado.nextInt();
int [] num=new int [n];
for ( i = 0; i < n; i++) {
System.out.print("");
System.out.print("EL ELEMENTO "+ (i+1) + " TIENE EL VALOR: ");
n1=teclado.nextInt();
num[i]=n1;
}
System.out.print("");
System.out.print("INGRESE EL NUMERO A BUSCAR: ");
nb=teclado.nextInt();
i=0;
while(i<num.length && sw==false){
if(num[i]==nb){
pos=i+1;
sw=true;
}
i++;
}
if(sw==true){
System.out.println("EL NUMERO FUE ENCONTRADO, ESTA EN LA POSICION: "+pos);
}
else
System.out.println("EL NUMERO NO SE ENCUENTRA");
}
}
Comentarios
Publicar un comentario