stack - Why does this priority queue implementation only print one value repeatedly? -


this program should print out values in order ascending order. displays 957.0 repeatedly. how display numbers in order?

import java.io.*; import java.util.*;   class priorityq {     public int maxsize;     public double[] quearray;     public int nitems;     //------     public priorityq(int s){         maxsize = s;         quearray = new double[maxsize];         nitems = 0;     }     //-----     public void insert(double item){         int j;          if(nitems == 0){             quearray[nitems++] = item;         }         else{             for(j = nitems-1; j >= 0; j--){                 if(item > quearray[j]){                     quearray[j + 1] = item;                 }                 else{                     break;                 }             }         quearray[j + 1] = item;         nitems++;         }     }      //-----     public double remove(){         return quearray[--nitems];     }     //-----     public double peekmin(){         return quearray[nitems - 1];     }     //-----     public boolean isempty(){         return(nitems == 0);     }     //-----     public boolean isfull(){         return(nitems == maxsize);     } }     //-----       public class priorityqapp{         public static void main(string[] args) throws ioexception{             priorityq thepq = new priorityq(5);             thepq.insert(546);             thepq.insert(687);             thepq.insert(36);             thepq.insert(98);             thepq.insert(957);              while(!thepq.isempty()){                 double item = thepq.remove();                 system.out.print(item + " ");             }             system.out.println("");         }     } 

you should save effort , use priority queue generic type double. if wanted descending order use comparator orders highest value before lowest, asked ascending.

your problem array contain many copies of 957. because of line in code:

if(item > quearray[j]){     quearray[j + 1] = item; } 

try:

import java.io.*; import java.util.*;  public class priorityqapp{     public static void main(string[] args) throws ioexception{         priorityqueue<double> thepq = new priorityqueue<double>(5);         thepq.add(546);         thepq.add(687);         thepq.add(36);         thepq.add(98);         thepq.add(957);          while(thepq.size() > 0){             double item = thepq.poll();             system.out.print(item + " ");         }         system.out.println("");     } } 

or can fix code print out queue in descending order leaving make print out in ascending order, block pointed before should read instead:

if(item < quearray[j]){     quearray[j + 1] = quearray[j]; } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -