BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

Algorithms - Queue/priority Queue





Bookmark and Share





bogotobogo.com site search:




Queue


Queue implementations:

  1. Example 8
    Queue Struct with linked list data structure.
  2. Example 8B
    Queue Class with linked list data structure.



Priority Queue

A priority queue is a data structure, and it supports the following two basic operations:

  1. insert
  2. pop an item with the largest key

To implement the priority queue, we can use either unordered or ordered sequence, implemented as linked list or as arrays:

  1. Ordered sequence
    This allows for constant-time remove the maximum and find the maximum,
    but we may have to go through the whole list to insert an item.
  2. Unordered sequence
    This allows constant-time insert
    but we may have to go through the whole list to find a maximum and remove the maximum.



Priority Queue - Sorted Linked List

The following code uses ordered linked list:

#include <iostream>
using namespace std;

typedef struct PriorityQueue
{
	int data;
	int pri;
	PriorityQueue *next;
} pQ;

class PQueue
{
public:
	PQueue();
	~PQueue();
	void push(int, int);
	int pop();
	void display();
private:
	pQ *head;
};

PQueue::PQueue()
{
	head = NULL;
}

void PQueue::push(int d, int pri)
{
	pQ *ptr = new pQ;
	ptr->data = d;
	ptr->pri = pri;
	ptr->next = NULL;

	if(head == NULL) {
		head = ptr;
		return;
	}

	pQ *cur = head;
	pQ *prev = head;
	while(cur) {
		if(pri > cur->pri) {
			if(cur == head) {
				pQ *old = head;
				head = ptr;
				head->next = old;
				return;
			}
			prev->next = ptr;
			ptr->next = cur;
			return;
		}
		if(cur->next == NULL) {
			cur->next = ptr;
			return;
		}
		prev = cur;
		cur = cur->next;
	}
}

int PQueue::pop()
{
	if(head == NULL) return -1;
	int val = head->data;
	pQ *old = head;
	if(head->next) {
		head = head->next;
		delete old;
	}
	return val;
}

void PQueue::display()
{
	pQ * cur = head;
	while(cur) {
		cout << cur->data <<":" << cur->pri << endl;
		cur = cur->next;
	}
}

int main()
{
	PQueue *myPQueue = new PQueue();
	myPQueue->push(4, 400);	
	myPQueue->push(5, 500);
	myPQueue->push(1, 100);
	myPQueue->push(2, 200);
	myPQueue->push(3, 300);

	myPQueue->display();

	cout << "pop " << myPQueue->pop() << endl;
	cout << "pop " << myPQueue->pop() << endl;
	cout << "pop " << myPQueue->pop() << endl;
	cout << "pop " << myPQueue->pop() << endl;
	cout << "pop " << myPQueue->pop() << endl;
	
	return 0;
}

Output:

5:500
4:400
3:300
2:200
1:100
pop 5
pop 4
pop 3
pop 2
pop 1



Priority Queue - Unordered Array

The following code uses unordered array, and index 0 not used:

#include <iostream>
using namespace std;

void swap(int&, int&);

class PQueue
{
public:
	PQueue(int sz) : N(0) { pq = new int[sz];}
	~PQueue() { delete[] pq; }
	void insert(int item) {pq[++N] = item;}
	int remove();
	bool isEmpty() { return N == 0; }
	void display();
private:
	int *pq;
	int N;
};

int PQueue::remove()
{
	int max = 0;
	for(int i = 1 ; i <= N; i++) 
		if(pq[max] < pq[i]) max = i;
	/* swap the max item with the last item */
	swap(pq[max], pq[N]);
	/* return the last item which is not the max, 
	   then reduce the array size by 1 */
	return pq[N--];
}

void PQueue::display()
{
	for(int i = 1; i <= N; i++) cout << pq[i] << " " ;
	cout << endl;
}

void swap(int &a;, int &b;)
{
	int temp = b;
	b = a;
	a = temp;
}

int main()
{
	// first item of array a is not used
	int a[] = {0, 19, 17, 16, 12, 9, 15, 1, 2, 11, 7, 3, 10, 14}; 
	int sz = sizeof(a)/sizeof(a[0]);
	PQueue *q = new PQueue(sz-1);
	
	for(int i = 1; i < sz; i++) {
		q->insert(a[i]);
	}

	q->display();

	for(int i = 1; i < sz; i++) {
		cout << "remove max " << q->remove() << endl;
		q->display();
	}

	return 0;
}

Output should look like this:

19 17 16 12 9 15 1 2 11 7 3 10 14
remove max 19
14 17 16 12 9 15 1 2 11 7 3 10
remove max 17
14 10 16 12 9 15 1 2 11 7 3
remove max 16
14 10 3 12 9 15 1 2 11 7
remove max 15
14 10 3 12 9 7 1 2 11
remove max 14
11 10 3 12 9 7 1 2
remove max 12
11 10 3 2 9 7 1
remove max 11
1 10 3 2 9 7
remove max 10
1 7 3 2 9
remove max 9
1 7 3 2
remove max 7
1 2 3
remove max 3
1 2
remove max 2
1
remove max 1

Here we used unordered sequence (array). If we use ordered array, we can remove the maximum and find the maximum in constant-time. But we may go through the whole list for insert while unordered array allows a constant-time insert but more work needed to find the maximum and remove the maximum.





Heap-based Priority Queue

In this example, we constructs a heap by inserting items one by one starting from an empty heap. Throughout the inserting process, we keep the array in heap order by moving sequentially through the array using siftUp(). The time complexity of the process is NlogN for the worst case, but on the average, it's linear time.

The code below is the extension of the previous example. To insert an element, we incremented N by 1, and add the new item at the end of the heap. Then, we used siftUp() to restore the max-heap condition. In the remove(), the heap size is decremented by 1, and we take the value to be returned from pq[1], which is actually pq[N] after the swap.

Note that index 0 is not used, and the valid array arrange is from pq[1] to pq[N].

#include <iostream>
using namespace std;

void swap(int&, int&);

class PQueue
{
public:
	PQueue(int sz) : N(0) { pq = new int[sz];}
	~PQueue() { delete[] pq; }
	void insert(int);
	int remove();
	bool isEmpty() { return N == 0; }
	void display();
	void siftDown(int*, int, int);
	void siftUp(int*, int);
private:
	int *pq;
	int N;
};

void PQueue::siftUp(int a[], int k)
{
	while(k > 1 && a[k] > a[k/2]) {
		swap(a[k], a[k/2]);
		k = k/2;
	}
}

void PQueue::siftDown(int a[], int k, int n)
{
	while(2*k <= n ) 
	{
		int child = 2*k;
		if(child < n && a[child] < a[child+1]) child++;
		if(a[k] < a[child]) {
		    swap(a[k], a[child]);
		    k = child;
		}
		else
		    return;
	}
}
void PQueue::insert(int item)
{
	pq[++N] = item;
	siftUp(pq, N); // N is the last index
}

// remove max element
int PQueue::remove()
{
	swap(pq[N], pq[1]);
	// N is the last index, pq[N] is the max about to be removed
	siftDown(pq, 1, N-1);  // move down
	return pq[N--];  // Now, N is the max item index
}

void PQueue::display()
{
	for(int i = 1; i <= N; i++) cout << pq[i] << " " ;
	cout << endl;
}

void swap(int &a;, int &b;)
{
	int temp = b;
	b = a;
	a = temp;
}

int main()
{
	int a[] = {0, 19, 17, 16, 12, 9, 15, 1, 2, 11, 7, 3, 10, 14};
	int sz = sizeof(a)/sizeof(a[0]);
	PQueue *q = new PQueue(sz-1);
	
	for(int i = 1; i < sz; i++) {
		q->insert(a[i]);
	}

	q->display();

	for(int i = 1; i < sz; i++) {
		cout << "remove max " << q->remove() << endl;
		q->display();
	}

	return 0;
}

When we insert a new element, we use siftUp() to restore max-heap condition by moving up the heap. Actually, we swap the node at k with its parent at k/2. We do this as long as a[k/2] < a[k] until we get to the top of the heap.

Output is:

19 17 16 12 9 15 1 2 11 7 3 10 14
remove max 19
17 14 16 12 9 15 1 2 11 7 3 10
remove max 17
16 14 15 12 9 10 1 2 11 7 3
remove max 16
15 14 10 12 9 3 1 2 11 7
remove max 15
14 12 10 11 9 3 1 2 7
remove max 14
12 11 10 7 9 3 1 2
remove max 12
11 9 10 7 2 3 1
remove max 11
10 9 3 7 2 1
remove max 10
9 7 3 1 2
remove max 9
7 2 3 1
remove max 7
3 2 1
remove max 3
2 1
remove max 2
1
remove max 1

As we see from the output, the array always keeps the max-heap condition.











Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong





LIST OF ALGORITHMS



Algorithms - Introduction

Bubble Sort

Bucket Sort

Counting Sort

Heap Sort

Insertion Sort

Merge Sort

Quick Sort

Radix Sort - LSD

Selection Sort

Shell Sort



Queue/Priority Queue - Using linked list & Heap

Stack Data Structure

Trie Data Structure

Binary Tree Data Structure - BST

Hash Map/Hash Table

Linked List Data Structure

Closest Pair of Points

Spatial Data Structure and Physics Engines



Recursive Algorithms

Dynamic Programming

Knapsack Problems - Discrete Optimization

(Batch) Gradient Descent in python and scikit



Uniform Sampling on the Surface of a Sphere.

Bayes' Rule

Monty Hall Paradox

Compression Algorithm - Huffman Codes

Shannon Entropy

Path Finding Algorithm - A*

Dijkstra's Shortest Path

Prim's spanning tree algorithm in Python

Bellman-Ford Shortest Path

Encryption/Cryptography Algorithms

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)



Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras




C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...


List of Design Patterns



Introduction

Abstract Factory Pattern

Adapter Pattern

Bridge Pattern

Chain of Responsibility

Command Pattern

Composite Pattern

Decorator Pattern

Delegation

Dependency Injection(DI) and Inversion of Control(IoC)

Façade Pattern

Factory Method

Model View Controller (MVC) Pattern

Observer Pattern

Prototype Pattern

Proxy Pattern

Singleton Pattern

Strategy Pattern

Template Method Pattern








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master