Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Heap {
- static int vetor[] ={15,21,23,48,35,70,67};
- static int lista = vetor.length;
- static int l;
- public static void main(String[] args) {
- Scanner sc = new Scanner (System.in);
- int op, tam=0, ind, num;
- do{
- System.out.println("\n Menu de opções - HEAP MÁXIMO");
- System.out.println("1-Números da lista");
- System.out.println("2- Consultar o elemento de maior prioridade");
- System.out.println("3- Remover o elemento de maior prioridade");
- System.out.println("4-Consultar toda a lista");
- System.out.println("5-Sair");
- System.out.println("Digite a sua opção:");
- op=sc.nextInt();
- if(op<1|| op>5){
- System.out.println("Opção inváloda!!!");
- }
- if(op==1){
- if(tam < vetor.length-1){
- tam++;
- for( l = 0; l < lista; l++){
- System.out.println(vetor[l]);
- }
- ind=tam;
- while(ind>1 && vetor[ind]<vetor[l]){
- vetor[ind]=vetor[ind];
- ind=ind;
- }
- vetor[ind]=vetor[tam];
- System.out.println("Número inserido");
- }else{
- System.out.println("Lista de prioridades lotada");
- }
- }
- if(op==2){
- if(tam==0){
- System.out.println("Lista de prioridades vazia!!");
- }else{
- System.out.println("Elemento de maior prioridade: " +vetor[1]);
- }
- }
- if(op==3){
- if(tam==0){
- System.out.println("Lista de prioridades vazia");
- }else{
- int maior_prior=vetor[1];
- vetor[1]=vetor[tam];
- tam--;
- heap_fica(1,tam);
- System.out.println("O elemento rovido:" +maior_prior);
- }
- }
- if(op==4){
- if(tam==0){
- System.out.println("Lista de prioridade vazia!!");
- }else{
- System.out.println("\n todos os elementos da lista de prioridade:\n");
- for(int j=1;j<=tam;j++){
- System.out.println(vetor[j]+"");
- }
- }
- }
- if(op==5){
- break;
- }
- }while(op!=6);
- }
- public static int pai (int x){
- return x/2;
- }
- private static void heap_fica(int i, int qtde) {
- int f_esq,f_dir,maior,aux;
- maior=i;
- if (2*i+1<=qtde){
- f_esq=2*i+1;
- f_dir=2*i;
- if(vetor[f_esq]>= vetor[f_dir] && vetor[f_esq] > vetor[i]){
- maior= 2*i+1;
- }else if(vetor[f_dir]>vetor[f_esq] && vetor[f_dir]>vetor[i]){
- maior=2*i;
- }else if(maior!=i){
- aux=vetor[i];
- vetor[i]=vetor[maior];
- vetor[maior]=aux;
- heap_fica(maior,qtde);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement