Laman

Powered By Blogger

Selasa, 25 Desember 2012

antrian prioritas (priority queue)

priority queue or a antrian prioritas, where each element of higher value will go and queue in front of the smaller, in the lab, I was asked to menginputkan queue manually, and not consecutively. after which the program will automatically sort the corresponding value of the character in the enqueue. This is similar to the way sorting. ie comparing the elements of the new entrance to the front element, if the element has a value greater then the element will be shifted left fence to meet a higher value.

#include <cstdlib>
#include <iostream>
#define maks 5

using namespace std;

class Queue{
friend ostream& operator<<(ostream&, const Queue&);
public :
Queue();
int penuh(int);
int kosong(int);
void cetak();
void enqueue();
char dequeue();

private :
char A[maks];
int banyak;
char x;
};

ostream& operator<<(ostream& out, const Queue& s){
cout<<”\nIsi Quueue sebanyak : “<<s.banyak<<” yaitu : “;
for(int i=0;i<s.banyak;i++)
out<<s.A[i]<<” “;
return out;
}

Queue::Queue(){
banyak=0;
for(int i=0;i<maks;i++)
A[i]=’0′;
}

int Queue::penuh(int s){
return s==maks?1:0;
}

int Queue::kosong(int s){
return s==0?1:0;
}

void Queue::cetak(){
cout<<”\nIsi Queue : “;
for(int i=0;i<banyak;i++)
cout<<A[i]<<” “;
}

void Queue::enqueue(){
cin>>x;
cout<<”Elemen :”<<x<<” masuk antrian”;
if(penuh(banyak))cout<<”queue penuh “;
else if(A[0]==’0′){
A[0]=x;
banyak++;
}
else{
int tempat=0;
while(A[tempat]>x)tempat++;
if(banyak!=tempat)
for(int i=banyak;i>=tempat;i–)
A[i+1] = A[i];
A[tempat]=x;
banyak++;
}
}

char Queue::dequeue(){
char temp=A[--banyak];
cout<<”\nDequeue elemen –> “<<temp;
A[banyak]=’0′;
return temp;
}

int main(int argc, char *argv[])
{
Queue p;
for(int i=1;i<=5;i++){
cout<<”masukan elemnt :”;p.enqueue();
cout<<endl;
}
cout<<p;

for(int i=1;i<=5;i++){
p.dequeue();cout<<p;
if(i==5) cout<<”\n\n\n element kosong”;
cout<<endl;
}
system(“PAUSE”);
return EXIT_SUCCESS;
}


Tidak ada komentar:

Posting Komentar