
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Kth smallest element after every insertion in C++
In this tutorial, we are going to find the k-th smallest element after every insertion.
We are going to use the min-heap to solve the problem. Let's see the steps to complete the program.
- Initialise the array with random data.
- Initialise the priority queue.
- Till k - 1 there won't be any k-th smallest element. So, print any symbol u like.
- Write a loop that iterates from k + 1 to n.
- Print the root of the min-heap.
- If the element is greater than the root of the min-heap, then pop the root and insert the element.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; void findKthSmallestElement(int elements[], int n, int k) { priority_queue<int, vector<int>, greater<int>> queue; for (int i= 0; i < k - 1; i++) { queue.push(elements[i]); cout << "- "; } queue.push(elements[k-1]); for (int i = k; i < n; i++) { cout << queue.top() << " "; if (elements[i] > queue.top()) { queue.pop(); queue.push(elements[i]); } } cout << queue.top() << endl; } int main() { int arr[] = {3, 5, 6, 2, 7, 8, 2, 3, 5, 9}; findKthSmallestElement(arr, 10, 5); return 0; }
Output
If you run the above code, then you will get the following result.
- - - - 2 3 3 3 5 5
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Articles
- Kth Smallest Element in a BST in Python
- Kth Smallest Element in a Sorted Matrix in Python
- Find maximum sum taking every Kth element in the array in C++
- Python – Extract Kth element of every Nth tuple in List
- Program to find kth smallest element in linear time in Python
- Kth Smallest Number in Multiplication Table in C++
- C++ Program to find kth Smallest Element by the Method of Partitioning the Array\n
- Find last element after deleting every second element in array of n integers in C++
- Program to find the kth smallest element in a Binary Search Tree in Python
- kth smallest/largest in a small range unsorted array in C++
- K-th smallest element after removing some integers from natural numbers in C++
- Smallest integer > 1 which divides every element of the given array: Using C++
- Program to find kth smallest n length lexicographically smallest string in python
- Python – Cross Join every Kth segment
- Find the Kth Smallest Sum of a Matrix With Sorted Rows in C++

Advertisements