/* Classe CPD
 * Métodos para classificação e pesquisa em vetores inteiros
 */

import java.util.*;
public class CPD {

	// Cria um vetor int de tamanho tam com elementos aleatórios <= max
	public static int[] criar(int tam, int max) {
		int[] vetor = new int[tam];
		Random r= new Random();
		for (int i = 0; i < tam; i++)
			vetor[i] = r.nextInt(max + 1);
		return vetor;  
	}

	//Imprime o vetor passado como parâmetro
	public static void imprimir(int[] vetor, boolean inverso) {
		if (!inverso)
			for(int x = 0; x < vetor.length; x++)
				System.out.print(vetor[x]+ " ");
		else
			for(int x = vetor.length-1; x >= 0;  x--)
				System.out.print(vetor[x]+ " ") ;

	}

	//Embaralha um vetor, devolvendo o resultado em outro vetor
	public static int[] embaralhar(int[] vetor) {
		int[] vetorRetorno = vetor.clone();
		int pos, tam = vetorRetorno.length;
		Random r = new Random();
		for (int i = 0; i < tam; i++) {
			//troca os elementos
			pos = r.nextInt(tam);
			trocaElemento(vetorRetorno,i,pos);
		}
		return vetorRetorno;  
	}

	//Exclui um elemento do vetor, redimensionando-0	
	public static int[] excluir(int[] vetor, int pos) {
		int indice, tam = vetor.length;
		for (indice = pos ; indice < tam - 1 ; indice++) {
			vetor[indice] = vetor[indice + 1];
		}
		int[] vetorRetorno = CPD.redimensionar(vetor,tam-1);
		return vetorRetorno;
	}

	//Inserir um elemento no vetor, redimensionando-0	
	public static int[] inserir(int[] vetor, int pos, int valor) {
		int[] vetorRetorno = CPD.redimensionar(vetor,vetor.length + 1);
		int indice, tam = vetorRetorno.length;
		for (indice = (tam - 1) ; indice > pos; indice--) {
			vetorRetorno[indice] = vetorRetorno[indice - 1];
		}
		vetorRetorno[pos] = valor;
		return vetorRetorno;
	}

	//Realiza uma pesquisa sequencial por valor dentro de vetor
	public static int pesqSeq(int[] vetor,int valor)  
	{
		int indice = -1; //Valor negativo caso não encontre
		int tam = vetor.length;
		int cont;
		for (cont = 0; cont < tam; cont++)
			if (vetor[cont] == valor)
			{
				indice = cont; //Interrompe a pesquisa caso encontre
				break;
			}
		return indice;     
	}

	//Redimensiona o vetor para o novo tamanho
	public static int[] redimensionar(int [] vetor, int novoTamanho) {
		int[] vetorRetorno = Arrays.copyOf(vetor,novoTamanho);
		return vetorRetorno;
	}    

	//Troca os valores entre 2 elementos do vetor
	public static void trocaElemento(int [] vetor, int indice1, int indice2) {
		int aux = vetor[indice1];
		vetor[indice1] = vetor[indice2];
		vetor[indice2] = aux;
	}

}   
