logo

Kas ir prioritārā rinda | Ievads prioritāšu rindā

A prioritārā rinda ir rindas veids, kas sakārto elementus, pamatojoties uz to prioritārajām vērtībām. Elementi ar augstākām prioritātes vērtībām parasti tiek izgūti pirms elementiem ar zemākām prioritātes vērtībām.

Prioritātes rindā katram elementam ir ar to saistīta prioritātes vērtība. Kad rindai pievienojat elementu, tas tiek ievietots pozīcijā, pamatojoties uz tā prioritātes vērtību. Piemēram, ja prioritārajai rindai pievienojat elementu ar augstu prioritātes vērtību, tas var tikt ievietots rindas priekšpusē, savukārt elements ar zemu prioritātes vērtību var tikt ievietots aizmugurē.



Ir vairāki veidi, kā ieviest prioritāro rindu, tostarp izmantojot masīvu, saistīto sarakstu, kaudzi vai bināro meklēšanas koku. Katrai metodei ir savas priekšrocības un trūkumi, un labākā izvēle būs atkarīga no jūsu lietojumprogrammas īpašajām vajadzībām.

Prioritātes rindas bieži tiek izmantotas reāllaika sistēmās, kur elementu apstrādes secībai var būt būtiskas sekas. Tos izmanto arī algoritmos, lai uzlabotu to efektivitāti, piemēram, Dijkstras algoritms īsākā ceļa atrašanai grafikā un A* meklēšanas algoritmu ceļa atrašanai.

Prioritātes rindas īpašības

Tātad prioritārā rinda ir paplašinājums rindā ar šādām īpašībām.



  • Katram vienumam ir ar to saistīta prioritāte.
  • Elements ar augstu prioritāti tiek izslēgts no rindas pirms elementa ar zemu prioritāti.
  • Ja diviem elementiem ir vienāda prioritāte, tie tiek apkalpoti atbilstoši to secībai rindā.

Tālāk norādītajā prioritātes rindā elementam ar maksimālo ASCII vērtību būs augstākā prioritāte. Vispirms tiek pasniegti elementi ar augstāku prioritāti.

Kā prioritārās rindas elementiem tiek piešķirta prioritāte?

Prioritātes rindā parasti prioritātes piešķiršanai tiek ņemta vērā elementa vērtība.



Piemēram, elementam ar augstāko vērtību tiek piešķirta augstākā prioritāte, bet elementam ar zemāko vērtību tiek piešķirta zemākā prioritāte. Var izmantot arī apgriezto gadījumu, t.i., elementam ar zemāko vērtību var piešķirt augstāko prioritāti. Arī prioritāti var piešķirt atbilstoši mūsu vajadzībām.

Prioritārās rindas darbības:

Tipiska prioritātes rinda atbalsta šādas darbības:

1) ievietošana prioritārajā rindā

Kad prioritārajā rindā tiek ievietots jauns elements, tas tiek pārvietots uz tukšo slotu no augšas uz leju un no kreisās uz labo pusi. Tomēr, ja elements nav pareizajā vietā, tas tiks salīdzināts ar vecākmezglu. Ja elements nav pareizā secībā, elementi tiek apmainīti. Apmaiņas process turpinās, līdz visi elementi ir novietoti pareizajā pozīcijā.

2) Dzēšana prioritārajā rindā

Kā jūs zināt, ka maksimālajā kaudzē maksimālais elements ir saknes mezgls. Un tas noņems elementu, kuram vispirms ir maksimālā prioritāte. Tādējādi jūs noņemat saknes mezglu no rindas. Šī noņemšana izveido tukšu slotu, kas tiks aizpildīta ar jaunu ievietošanu. Pēc tam tas salīdzina tikko ievietoto elementu ar visiem rindā esošajiem elementiem, lai saglabātu kaudzes invariantu.

3) Ielūkojieties prioritārajā rindā

Šī darbība palīdz atgriezt maksimālo elementu no Max Heap vai minimālo elementu no Min Heap, neizdzēšot mezglu no prioritārās rindas.

Prioritāro rindu veidi:

1) Prioritātes rinda augošā secībā

Kā norāda nosaukums, augošā secībā prioritātes rindā elementam ar zemāku prioritātes vērtību prioritāšu sarakstā tiek piešķirta augstāka prioritāte. Piemēram, ja mums ir šādi elementi prioritārā rindā, kas sakārtoti augošā secībā, piemēram, 4,6,8,9,10. Šeit 4 ir mazākais skaitlis, tāpēc tam tiks piešķirta augstākā prioritāte prioritārajā rindā, un tāpēc, kad mēs noņemam rindu no šāda veida prioritārās rindas, 4 noņems no rindas un rindā atgriež 4.

2) Prioritātes rinda dilstošā secībā

Kā jūs, iespējams, zināt, saknes mezgls ir maksimālais elements maksimālajā kaudzē. Tas arī vispirms noņems elementu ar augstāko prioritāti. Tā rezultātā saknes mezgls tiek noņemts no rindas. Šī dzēšana atstāj tukšu vietu, kas turpmāk tiks aizpildīta ar jauniem ievietojumiem. Pēc tam kaudzes invariants tiek uzturēts, salīdzinot tikko ievietoto elementu ar visiem citiem ierakstiem rindā.

Prioritāro rindu veidi

Prioritāro rindu veidi

Atšķirība starp prioritāro rindu un parasto rindu?

Elementiem rindā nav pievienota prioritāte, tiek ieviests FIFO noteikums, savukārt prioritārā rindā elementiem ir prioritāte. Vispirms tiek pasniegti elementi ar augstāku prioritāti.

Kā ieviest prioritāro rindu?

Prioritātes rindu var ieviest, izmantojot šādas datu struktūras:

kas ir Linux failu sistēma
  • Masīvi
  • Saistītais saraksts
  • Kaudzes datu struktūra
  • Binārais meklēšanas koks

Apspriedīsim visu to sīkāk.

1) Ieviesiet prioritāro rindu, izmantojot masīvu:

Vienkārša ieviešana ir šādas struktūras masīva izmantošana.

struct item {
int vienums;
int priority;
}

    enqueue(): šo funkciju izmanto, lai rindā ievietotu jaunus datus. dequeue(): šī funkcija no rindas noņem elementu ar augstāko prioritāti. peek()/top(): šī funkcija tiek izmantota, lai rindā iegūtu visaugstākās prioritātes elementu, nenoņemot to no rindas.

Masīvi

rindā ()

attiecīgi ()

palūrēt ()

Laika sarežģītība

O(1)

O(n)

O(n)

C++




// C++ program to implement Priority Queue> // using Arrays> #include> using> namespace> std;> // Structure for the elements in the> // priority queue> struct> item {> >int> value;> >int> priority;> };> // Store the element of a priority queue> item pr[100000];> // Pointer to the last index> int> size = -1;> // Function to insert a new element> // into priority queue> void> enqueue(>int> value,>int> priority)> {> >// Increase the size> >size++;> >// Insert the element> >pr[size].value = value;> >pr[size].priority = priority;> }> // Function to check the top element> int> peek()> {> >int> highestPriority = INT_MIN;> >int> ind = -1;> >// Check for the element with> >// highest priority> >for> (>int> i = 0; i <= size; i++) {> >// If priority is same choose> >// the element with the> >// highest value> >if> (highestPriority == pr[i].priority && ind>-1> >&& pr[ind].value highestPriority = pr[i].priority; ind = i; } else if (highestPriority highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind; } // Function to remove the element with // the highest priority void dequeue() { // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--; } // Driver Code int main() { // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; // Dequeue the top element dequeue(); // Check the top element ind = peek(); cout << pr[ind].value << endl; return 0; }>

>

>

Java




// Java program to implement Priority Queue> // using Arrays> import> java.util.*;> // Structure for the elements in the> // priority queue> class> item {> >public> int> value;> >public> int> priority;> };> class> GFG {> >// Store the element of a priority queue> >static> item[] pr =>new> item[>100000>];> >// Pointer to the last index> >static> int> size = ->1>;> >// Function to insert a new element> >// into priority queue> >static> void> enqueue(>int> value,>int> priority)> >{> >// Increase the size> >size++;> >// Insert the element> >pr[size] =>new> item();> >pr[size].value = value;> >pr[size].priority = priority;> >}> >// Function to check the top element> >static> int> peek()> >{> >int> highestPriority = Integer.MIN_VALUE;> >int> ind = ->1>;> >// Check for the element with> >// highest priority> >for> (>int> i =>0>; i <= size; i++) {> >// If priority is same choose> >// the element with the> >// highest value> >if> (highestPriority == pr[i].priority> >&& ind>->1> >&& pr[ind].value highestPriority = pr[i].priority; ind = i; } else if (highestPriority highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind; } // Function to remove the element with // the highest priority static void dequeue() { // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--; } public static void main(String[] args) { // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); System.out.println(pr[ind].value); // Dequeue the top element dequeue(); // Check the top element ind = peek(); System.out.println(pr[ind].value); // Dequeue the top element dequeue(); // Check the top element ind = peek(); System.out.println(pr[ind].value); } } // this code is contributed by phasing17>

>

>

Python3




jvm java

import> sys> # Structure for the elements in the> # priority queue> class> item :> >value>=> 0> >priority>=> 0> class> GFG :> > ># Store the element of a priority queue> >pr>=> [>None>]>*> (>100000>)> > ># Pointer to the last index> >size>=> ->1> > ># Function to insert a new element> ># into priority queue> >@staticmethod> >def> enqueue( value, priority) :> > ># Increase the size> >GFG.size>+>=> 1> > ># Insert the element> >GFG.pr[GFG.size]>=> item()> >GFG.pr[GFG.size].value>=> value> >GFG.pr[GFG.size].priority>=> priority> > ># Function to check the top element> >@staticmethod> >def> peek() :> >highestPriority>=> ->sys.maxsize> >ind>=> ->1> > ># Check for the element with> ># highest priority> >i>=> 0> >while> (i <>=> GFG.size) :> > ># If priority is same choose> ># the element with the> ># highest value> >if> (highestPriority>=>=> GFG.pr[i].priority>and> ind>>>1> and> GFG.pr[ind].value highestPriority = GFG.pr[i].priority ind = i elif(highestPriority highestPriority = GFG.pr[i].priority ind = i i += 1 # Return position of the element return ind # Function to remove the element with # the highest priority @staticmethod def dequeue() : # Find the position of the element # with highest priority ind = GFG.peek() # Shift the element one index before # from the position of the element # with highest priority is found i = ind while (i GFG.pr[i] = GFG.pr[i + 1] i += 1 # Decrease the size of the # priority queue by one GFG.size -= 1 @staticmethod def main( args) : # Function Call to insert elements # as per the priority GFG.enqueue(10, 2) GFG.enqueue(14, 4) GFG.enqueue(16, 4) GFG.enqueue(12, 3) # Stores the top element # at the moment ind = GFG.peek() print(GFG.pr[ind].value) # Dequeue the top element GFG.dequeue() # Check the top element ind = GFG.peek() print(GFG.pr[ind].value) # Dequeue the top element GFG.dequeue() # Check the top element ind = GFG.peek() print(GFG.pr[ind].value) if __name__=='__main__': GFG.main([]) # This code is contributed by aadityaburujwale.>

>

>

C#




// C# program to implement Priority Queue> // using Arrays> using> System;> // Structure for the elements in the> // priority queue> public> class> item {> >public> int> value;> >public> int> priority;> };> public> class> GFG> {> > >// Store the element of a priority queue> >static> item[] pr =>new> item[100000];> >// Pointer to the last index> >static> int> size = -1;> >// Function to insert a new element> >// into priority queue> >static> void> enqueue(>int> value,>int> priority)> >{> >// Increase the size> >size++;> > >// Insert the element> >pr[size] =>new> item();> >pr[size].value = value;> >pr[size].priority = priority;> >}> > >// Function to check the top element> >static> int> peek()> >{> >int> highestPriority =>int>.MinValue;> >int> ind = -1;> > >// Check for the element with> >// highest priority> >for> (>int> i = 0; i <= size; i++) {> > >// If priority is same choose> >// the element with the> >// highest value> >if> (highestPriority == pr[i].priority && ind>-1> >&& pr[ind].value highestPriority = pr[i].priority; ind = i; } else if (highestPriority highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind; } // Function to remove the element with // the highest priority static void dequeue() { // Find the position of the element // with highest priority int ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (int i = ind; i pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--; } public static void Main(string[] args) { // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment int ind = peek(); Console.WriteLine(pr[ind].value); // Dequeue the top element dequeue(); // Check the top element ind = peek(); Console.WriteLine(pr[ind].value); // Dequeue the top element dequeue(); // Check the top element ind = peek(); Console.WriteLine(pr[ind].value); } } //this code is contributed by phasing17>

>

>

Javascript




// JavaScript program to implement Priority Queue> // using Arrays> // Structure for the elements in the> // priority queue> class item {> >constructor()> >{> >this>.value;> >this>.priority;> >}> };> // Store the element of a priority queue> let pr = [];> for> (>var> i = 0; i <100000; i++)> >pr.push(>new> item());> // Pointer to the last index> let size = -1;> // Function to insert a new element> // into priority queue> function> enqueue(value, priority)> {> >// Increase the size> >size++;> >// Insert the element> >pr[size] =>new> item();> >pr[size].value = value;> >pr[size].priority = priority;> }> // Function to check the top element> function> peek()> {> >let highestPriority = Number.MIN_SAFE_INTEGER;> >let ind = -1;> >// Check for the element with> >// highest priority> >for> (>var> i = 0; i <= size; i++) {> >// If priority is same choose> >// the element with the> >// highest value> >if> (highestPriority == pr[i].priority && ind>-1> >&& pr[ind].value highestPriority = pr[i].priority; ind = i; } else if (highestPriority highestPriority = pr[i].priority; ind = i; } } // Return position of the element return ind; } // Function to remove the element with // the highest priority function dequeue() { // Find the position of the element // with highest priority let ind = peek(); // Shift the element one index before // from the position of the element // with highest priority is found for (var i = ind; i pr[i] = pr[i + 1]; } // Decrease the size of the // priority queue by one size--; } // Function Call to insert elements // as per the priority enqueue(10, 2); enqueue(14, 4); enqueue(16, 4); enqueue(12, 3); // Stores the top element // at the moment let ind = peek(); console.log(pr[ind].value); // Dequeue the top element dequeue(); // Check the top element ind = peek(); console.log(pr[ind].value); // Dequeue the top element dequeue(); // Check the top element ind = peek(); console.log(pr[ind].value); // this code is contributed by phasing17>

>

>

Izvade

16 14 12>

Piezīme: Lasīt Šis raksts lai iegūtu sīkāku informāciju.

2) Ieviesiet prioritāro rindu, izmantojot saistīto sarakstu:

LinkedList ieviešanā ieraksti tiek sakārtoti dilstošā secībā, pamatojoties uz to prioritāti. Augstākās prioritātes elements vienmēr tiek pievienots prioritātes rindas priekšpusē, kas tiek veidota, izmantojot saistītos sarakstus. Funkcijas, piemēram push () , pop () , un palūrēt () tiek izmantoti, lai ieviestu prioritāro rindu, izmantojot saistītu sarakstu, un ir izskaidroti šādi:

    push(): šo funkciju izmanto, lai rindā ievietotu jaunus datus. pop(): šī funkcija no rindas noņem elementu ar augstāko prioritāti. peek() / top(): šī funkcija tiek izmantota, lai rindā iegūtu visaugstākās prioritātes elementu, nenoņemot to no rindas.

Saistītais saraksts

push ()

pop ()

palūrēt ()

Laika sarežģītība

O(n)

O(1)

O(1)

C++

kartes atkārtošana java




// C++ code to implement Priority Queue> // using Linked List> #include> using> namespace> std;> // Node> typedef> struct> node {> >int> data;> >// Lower values indicate> >// higher priority> >int> priority;> >struct> node* next;> } Node;> // Function to create a new node> Node* newNode(>int> d,>int> p)> {> >Node* temp = (Node*)>malloc>(>sizeof>(Node));> >temp->dati = d;> >temp->prioritāte = p;> >temp->nākamais = NULL;> >return> temp;> }> // Return the value at head> int> peek(Node** head) {>return> (*head)->dati; }> // Removes the element with the> // highest priority form the list> void> pop(Node** head)> {> >Node* temp = *head;> >(*head) = (*head)->nākamais;> >free>(temp);> }> // Function to push according to priority> void> push(Node** head,>int> d,>int> p)> {> >Node* start = (*head);> >// Create new Node> >Node* temp = newNode(d, p);> >// Special Case: The head of list has> >// lesser priority than new node> >if> ((*head)->prioritāte // Insert New Node before head temp->next = *head; (*galva) = temp; } else { // Pārejiet pa sarakstu un atrodiet // pozīciju, lai ievietotu jaunu mezglu, while (sākt->next != NULL && start->next->priority> p) { start = start->next; } // Vai nu saraksta beigās // vai vajadzīgajā pozīcijā temp->next = start->next; sākums->nākamais = temp; } } // Funkcija, kas jāpārbauda, ​​vai saraksts ir tukšs int isEmpty(Node** head) { return (*head) == NULL; } // Draivera kods int main() { // Izveidot prioritāro rindu // 7->4->5->6 Node* pq = newNode(4, 1); push(&pq, 5, 2); push(&pq, 6, 3); push(&pq, 7, 0); while (!isEmpty(&pq)) { cout<< ' ' << peek(&pq); pop(&pq); } return 0; }>

>

>

Java




// Java code to implement Priority Queue> // using Linked List> import> java.util.* ;> class> Solution> {> // Node> static> class> Node {> >int> data;> > >// Lower values indicate higher priority> >int> priority;> >Node next;> > }> static> Node node =>new> Node();> > // Function to Create A New Node> static> Node newNode(>int> d,>int> p)> {> >Node temp =>new> Node();> >temp.data = d;> >temp.priority = p;> >temp.next =>null>;> > >return> temp;> }> > // Return the value at head> static> int> peek(Node head)> {> >return> (head).data;> }> > // Removes the element with the> // highest priority from the list> static> Node pop(Node head)> {> >Node temp = head;> >(head) = (head).next;> >return> head;> }> > // Function to push according to priority> static> Node push(Node head,>int> d,>int> p)> {> >Node start = (head);> > >// Create new Node> >Node temp = newNode(d, p);> > >// Special Case: The head of list has lesser> >// priority than new node. So insert new> >// node before head node and change head node.> >if> ((head).priority // Insert New Node before head temp.next = head; (head) = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority>p) {sākt = start.next; } // Vai nu saraksta beigās // vai vajadzīgajā pozīcijā temp.next = start.next; start.next = temp; } atgriešanās galva; } // Funkcija, kas jāpārbauda, ​​vai saraksts ir tukšs static int isEmpty(Node head) { return ((head) == null)?1:0; } // Draivera kods public static void main(String args[]) { // Izveidot prioritāro rindu // 7.4.5.6 Node pq = newNode(4, 1); pq =push(pq, 5, 2); pq =push(pq, 6, 3); pq =push(pq, 7, 0); while (isEmpty(pq)==0) { System.out.printf('%d ', peek(pq)); pq=pop(pq); } } } // Šo kodu nodrošina ishankhandelwals.>>

> 




# Python3 code to implement Priority Queue> # using Singly Linked List> # Class to create new node which includes> # Node Data, and Node Priority> class> PriorityQueueNode:> >def> _init_(>self>, value, pr):> >self>.data>=> value> >self>.priority>=> pr> >self>.>next> => None> # Implementation of Priority Queue> class> PriorityQueue:> >def> _init_(>self>):> >self>.front>=> None> ># Method to check Priority Queue is Empty> ># or not if Empty then it will return True> ># Otherwise False> >def> isEmpty(>self>):> >return> True> if> self>.front>=>=> None> else> False> ># Method to add items in Priority Queue> ># According to their priority value> >def> push(>self>, value, priority):> ># Condition check for checking Priority> ># Queue is empty or not> >if> self>.isEmpty()>=>=> True>:> ># Creating a new node and assigning> ># it to class variable> >self>.front>=> PriorityQueueNode(value,> >priority)> ># Returning 1 for successful execution> >return> 1> >else>:> ># Special condition check to see that> ># first node priority value> >if> self>.front.priority # Creating a new node newNode = PriorityQueueNode(value, priority) # Updating the new node next value newNode.next = self.front # Assigning it to self.front self.front = newNode # Returning 1 for successful execution return 1 else: # Traversing through Queue until it # finds the next smaller priority node temp = self.front while temp.next: # If same priority node found then current # node will come after previous node if priority>= temp.next.priority: break temp = temp.next newNode = PriorityQueueNode(vērtība, prioritāte) newNode.next = temp.next temp.next = newNode # Atgriež 1 veiksmīgai izpildei return 1 # Augstas prioritātes vienuma # noņemšanas metode no Priority Queue def pop(self): # Pārbaudes stāvokļa pārbaude # Prioritātes rinda ir tukša vai nav, ja self.isEmpty() == True: return else: # Augstas prioritātes mezgla noņemšana no # Prioritātes rindas un priekšējā # atjaunināšana ar nākamo node self.front = self.front.next return 1 # Augstas prioritātes mezgla atgriešanas metode # vērtība Nenoņem def peek(self): # Pārbaudes stāvokļa pārbaude Prioritāte # Rinda ir tukša vai nav, ja self.isEmpty() == True: return else: return self.front.data # Metode, lai izietu cauri prioritātei # Rindas def traverse(self): # Pārbaudes stāvokļa pārbaude Prioritāte # Rinda ir tukša vai nav, ja self.isEmpty() == True: return ' Rinda ir tukša!' else: temp = self.front while temp: print(temp.data, end=' ') temp = temp.next # Draivera kods if _name_ == '_main_': # Izveidojot prioritātes # rindas gadījums un vērtību pievienošana # 7 -> 4 -> 5 -> 6 pq = PriorityQueue() pq.push(4, 1) pq.push(5, 2) pq.push(6, 3) pq .push(7, 0) # Pārvietošanās caur prioritāro rindu pq.traverse() # Augstākās prioritātes vienuma # noņemšana prioritārajai rindai pq.pop()>

>

>

C#




// C# code to implement Priority Queue> // using Linked List> using> System;> class> GFG> {> >// Node> >public> class> Node> >{> >public> int> data;> >// Lower values indicate> >// higher priority> >public> int> priority;> >public> Node next;> >}> >public> static> Node node =>new> Node();> >// Function to Create A New Node> >public> static> Node newNode(>int> d,>int> p)> >{> >Node temp =>new> Node();> >temp.data = d;> >temp.priority = p;> >temp.next =>null>;> >return> temp;> >}> >// Return the value at head> >public> static> int> peek(Node head)> >{> >return> (head).data;> >}> >// Removes the element with the> >// highest priority from the list> >public> static> Node pop(Node head)> >{> >Node temp = head;> >(head) = (head).next;> >return> head;> >}> >// Function to push according to priority> >public> static> Node push(Node head,> >int> d,>int> p)> >{> >Node start = (head);> >// Create new Node> >Node temp = newNode(d, p);> >// Special Case: The head of list> >// has lesser priority than new node.> >// So insert new node before head node> >// and change head node.> >if> ((head).priority { // Insert New Node before head temp.next = head; (head) = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority>p) {sākt = start.next; } // Vai nu saraksta beigās // vai vajadzīgajā pozīcijā temp.next = start.next; start.next = temp; } atgriešanās galva; } // Funkcija, lai pārbaudītu, vai saraksts ir tukšs public static int isEmpty(Node head) { return ((head) == null) ? 1:0; } // Draivera kods public static void Main(string[] args) { // Izveidot prioritāro rindu // 7.4.5.6 Node pq = newNode(4, 1); pq = push(pq, 5, 2); pq = push(pq, 6, 3); pq = push(pq, 7, 0); while (isEmpty(pq) == 0) { Console.Write('{0:D} ', peek(pq)); pq = pop(pq); } } } // Šo kodu nodrošina ishankhandelwals.>>

> 




python rstrip

// JavaScript code to implement Priority Queue> // using Linked List> // Node> class Node {> >// Lower values indicate> >// higher priority> >constructor() {> >this>.data = 0;> >this>.priority = 0;> >this>.next =>null>;> >}> }> var> node =>new> Node();> // Function to Create A New Node> function> newNode(d, p) {> >var> temp =>new> Node();> >temp.data = d;> >temp.priority = p;> >temp.next =>null>;> >return> temp;> }> // Return the value at head> function> peek(head) {> >return> head.data;> }> // Removes the element with the> // highest priority from the list> function> pop(head) {> >var> temp = head;> >head = head.next;> >return> head;> }> // Function to push according to priority> function> push(head, d, p) {> >var> start = head;> >// Create new Node> >var> temp = newNode(d, p);> >// Special Case: The head of list> >// has lesser priority than new node.> >// So insert new node before head node> >// and change head node.> >if> (head.priority // Insert New Node before head temp.next = head; head = temp; } else { // Traverse the list and find a // position to insert new node while (start.next != null && start.next.priority>p) {sākt = start.next; } // Vai nu saraksta beigās // vai vajadzīgajā pozīcijā temp.next = start.next; start.next = temp; } atgriešanās galva; } // Pārbaudāmā funkcija ir tukša funkcija isEmpty(head) { return head == null ? 1:0; } // Draivera kods // Prioritātes rindas izveide // 7.4.5.6 var pq = newNode(4, 1); pq = push(pq, 5, 2); pq = push(pq, 6, 3); pq = push(pq, 7, 0); while (isEmpty(pq) == 0) { console.log(peek(pq),' '); pq = pop(pq); } // Šo kodu nodrošina ishankhandelwals.>>

> 

6 5 4 7>

Plašāku informāciju skatiet šajā rakstā.

Piezīme: Mēs varam arī izmantot Saistīto sarakstu, visu darbību laika sarežģītība ar saistīto sarakstu paliek tāda pati kā masīvam. Saistītā saraksta priekšrocība ir dzēstAugstākā prioritāte() var būt efektīvāki, jo mums nav jāpārvieto priekšmeti.

3) Ieviesiet prioritāro rindu, izmantojot kaudzes:

Binārā kaudze parasti tiek dota priekšroka prioritāro rindu ieviešanai, jo kaudzes nodrošina labāku veiktspēju salīdzinājumā ar masīviem vai LinkedList. Ņemot vērā kaudzes īpašības, ieraksts ar lielāko taustiņu atrodas augšpusē un to var nekavējoties noņemt. Tomēr atlikušo atslēgu kaudzes rekvizīta atjaunošanai būs nepieciešams laiks O(log n). Tomēr, ja nekavējoties jāievieto cits ieraksts, daļu no šī laika var apvienot ar O(log n) laiku, kas nepieciešams jaunā ieraksta ievietošanai. Tādējādi prioritārās rindas kā kaudzes attēlošana izrādās izdevīga lielam n, jo tā tiek efektīvi attēlota blakus esošajā krātuvē un tiek garantēta, ka gan ievietošanai, gan dzēšanai ir nepieciešams tikai logaritmisks laiks. Darbības ar bināro kaudzi ir šādas:

    insert(p): ievieto jaunu elementu ar prioritāti p. extractMax(): izvelk elementu ar maksimālu prioritāti. remove(i): noņem elementu, uz kuru norāda iterators i. getMax(): atgriež elementu ar maksimālu prioritāti. changePriority(i, p): maina tā elementa prioritāti, uz kuru norāda i uz lpp .

Binārā kaudze

ievietot ()

noņemt ()

palūrēt ()

Laika sarežģītība

O(log n)

O(log n)

O(1)

Informāciju par koda ieviešanu skatiet šajā rakstā.

4) Ieviesiet prioritāro rindu, izmantojot bināro meklēšanas koku:

Lai ieviestu prioritāro rindu, var izmantot arī pašbalansējošu bināro meklēšanas koku, piemēram, AVL koku, sarkanmelnu koku utt. Tādas darbības kā peek(), insert() un delete() var veikt, izmantojot BST.

Binārais meklēšanas koks palūrēt () ievietot () dzēst()
Laika sarežģītība O(1) O(log n) O(log n)

Prioritātes rindas lietojumprogrammas:

  • CPU plānošana
  • Grafiku algoritmi, piemēram, Dijkstra īsākā ceļa algoritms, Prim minimālais aptverošais koks utt.
  • Stack ieviešana
  • Visas prioritātes rindas lietojumprogrammas
  • Prioritātes rinda programmā C++
  • Prioritātes rinda Java
  • Prioritātes rinda Python
  • Prioritātes rinda JavaScript
  • Jaunākie raksti par prioritāro rindu!