BOm galera , fiz esse prog .ae. mas eu acho que ele esta muito complicado alguem conhece uma forma mais facil de fazer ? que use busca binaria , guardando os indices que tem elementos iguais !
//Achar o indice o indice dos números iguais usando busca binaria
// exemplo 1 2 3
// 1 1 1
// indices iguais 1 2 3
// n iguais 3
import javax.swing.*;
public class Exer5{
public static void bolha ( int v [ ] ) {
for ( int i = 0 ; i < v.length ; i++ ) {
for ( int j = 0 ; j < v.length - i - 1 ; j++ ) {
if ( v[j] > v[j+ 1 ] ) {
int aux = v[j];
v[j] = v[j+1];
v[j+1] = aux;
}
}
}
}
public static int qtdN_Iguais ( int v[ ] , int p ) {
int cont=0;
for ( int i = 0 ; i < v.length ; i++ ) {
if ( v[i] == p ){
cont ++;
}
}
return cont;
}
public static int buscaInd ( int v[ ] , int p ) {
int inicio =0 ;
int meio ;
final int n = v.length ;
int fim = n - 1;
int indiceP =0;
while ( inicio <= fim ) {
meio = ( inicio+ fim ) / 2 ;
if ( v[meio ] == p ){
return meio;
}
else
if ( v[meio ] > p ) {
fim = meio -1;
}
else{
inicio = meio + 1;
}
}
return -1;
}
public static String indIguais ( int v[ ] , int p ){
int indiceN = buscaInd ( v , p );
int ant = indiceN ;
int suc = indiceN;
int fim = v.length - 1;
int inic = 0;
String saida ="";
if ( v [ant - 1 ] != p && v[suc + 1 ] !=p){
saida = saida + " " + indiceN + "," ;
return saida;
}
else if ( indiceN == 0 ){
int i = 0;
while ( i < v.length - 1 && v[i] == p ){
saida = saida + " " + i + ",";
i++;
}
return saida;
}
else if ( indiceN == v.length - 1 ){
int i = 0;
while ( i >= 0 && v[i] == p ){
saida = saida + " " + i + ",";
i--;
}
return saida;
}
else {
int i = ant;
saida = saida + " " + ant;
while ( i >= 1 ){
if ( v[i - 1 ] == p ){
saida = saida + " " + (i-1) ;
}
i--;
}
int j = suc;
while ( j < v.length -1 ){
if ( ( v[j+1] == p ) ){
saida = saida + " " + (j+1)+ ",";
}
j ++;
}
return saida ;
}
}
public static void main ( String [ ] args ) {
int v [ ] ;
int tamanho = Integer.parseInt ( JOptionPane.showInputDialog (null, "quantidade de elementos de vetor"));
v = new int [ tamanho];
String aux = " ";
for ( int i = 0 ; i < v.length ; i++ ) {
v[i] = Integer.parseInt ( JOptionPane.showInputDialog (null, "Entre com o numero da posição " +(i+1)));
}
bolha(v);
String saida ="";
for ( int i = 0 ; i < v.length ; i++ ) {
saida =saida + v[i]+ ",";
}
int p = Integer.parseInt ( JOptionPane.showInputDialog (null, "Informe o Numero para procurar "));
if ( buscaInd ( v , p) != - 1 ){
JOptionPane.showMessageDialog ( null, " indices do número igual ao procurado"+
indIguais(v,p) + "\n quantidade de números iguais = "+ qtdN_Iguais(v,p)+ "\n \n numeros que estão no vetor {" + saida + "}");
}
else{
JOptionPane.showMessageDialog ( null, " O Número procurado não esta no array \n numeros que estão no vetor {" + saida + "}");
}
}
}