logologo
  • Dashboard
  • Features
  • AI Tools
  • FAQs
  • Jobs
  • Modus
logologo

We source, screen & deliver pre-vetted developers—so you only interview high-signal candidates matched to your criteria.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Certifications
  • Topics
  • Collections
  • Articles
  • Services

AI Tools

  • AI Interviewer
  • Xperto AI
  • Pre-Vetted Top Developers

Procodebase © 2025. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Sort a Nearly Sorted Array Using Heap

author
Generated by
Parveen Sharma

16/11/2024

Sorting

Sign in to read full article

Sorting is a fundamental operation in programming, often encountered in various applications. However, when dealing with a nearly sorted array—where elements are only slightly out of order—it can be more efficient to leverage specialized algorithms. In this blog post, we will delve into using the heap data structure to sort a nearly sorted array effectively, especially within the context of Java.

Understanding a Nearly Sorted Array

A nearly sorted array is one where each element is at most k positions away from its target position. For example, consider the array:

int[] arr = {3, 2, 1, 5, 4};

If we consider k = 2, then every element is at most 2 indices away from where it should be in a sorted version of the array.

Why Use a Heap Data Structure?

The heap data structure is ideal for this scenario for the following reasons:

  1. Time Complexity: The time complexity for heap operations (insertion and deletion) is O(log k), making it efficient for sorting nearly sorted arrays with k elements.

  2. Space Efficiency: Using a min-heap to maintain the smallest k+1 elements allows us to sort the array without using excessive additional space.

  3. Simplicity: Once the heap is established, extracting the minimum element becomes a simple operation, making sorting user-friendly.

Step-by-Step Approach to Sorting

Here’s how you can implement the sort using a min-heap:

Step 1: Initialize the Min-Heap

To sort a nearly sorted array, we first build a min-heap of size k+1. This heap will help us identify the smallest element among the nearest unsorted values.

Step 2: Insert Elements into the Heap

Insert the first k + 1 elements of the array into the min-heap.

Step 3: Sort the Array

  • After the heap is built, we will keep extracting the minimum element from the heap and put it back into the original array.
  • Then, if there are more elements left in the array, we insert the next element into the heap.

Step 4: Empty the Heap

Once all elements are processed, we can extract the remaining elements from the heap and place them in the array.

Code Implementation

Here is a complete implementation in Java:

import java.util.PriorityQueue; public class NearlySortedArray { public static int[] sortKSortedArray(int[] arr, int k) { // Create a min-heap PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // Output array int[] result = new int[arr.length]; int index = 0; // Build the heap with the first k+1 elements for (int i = 0; i <= Math.min(k, arr.length - 1); i++) { minHeap.add(arr[i]); } // Process the remaining elements in the array for (int i = k + 1; i < arr.length; i++) { // Extract the minimum from the heap and add it to the result result[index++] = minHeap.poll(); // Add the current element to the heap minHeap.add(arr[i]); } // Extract remaining elements from the heap while (!minHeap.isEmpty()) { result[index++] = minHeap.poll(); } return result; } public static void main(String[] args) { int[] arr = {3, 2, 1, 5, 4}; int k = 2; int[] sortedArray = sortKSortedArray(arr, k); // Print the sorted array System.out.println("Sorted Array: "); for (int num : sortedArray) { System.out.print(num + " "); } } }

Explanation of the Code

  • We use a PriorityQueue in Java to create a min-heap.
  • We first fill the heap with the initial k + 1 elements.
  • We then iterate through the rest of the array, continuously removing the smallest element from the heap and adding new elements.
  • Finally, we extract any remaining elements in the heap to complete the sorted array.

Time Complexity Analysis

The overall time complexity of this sorting method is O(n log k), where n is the number of elements in the array. This is efficient given the constraints posed by the nearly sorted nature of the input array.

By using a heap, we take advantage of the structural properties that allow us to perform sorting in a more efficient manner than traditional algorithms like quicksort or mergesort, especially when the data is nearly in order.

In Summary

Sorting a nearly sorted array using a heap is not only efficient but also a great way to optimize your sorting algorithms in situations where data order is nearly complete. This approach utilizes a priority queue effectively, allowing for both natural programming flow and performance benefits, making it a valuable technique for any programmer's toolkit.

Popular Tags

SortingHeapPriority Queue

Share now!

Like & Bookmark!

Related Collections

  • Top 20 DSA Interview Questions Mastery

    23/09/2024 | DSA

  • Mastering Arrays : The Basic Data Structure

    06/12/2024 | DSA

  • Mastering Bit Manipulation: Unlocking Binary Power

    08/12/2024 | DSA

  • DSA Mastery for Interviews

    23/09/2024 | DSA

  • Advanced String-based Interview Techniques

    15/11/2024 | DSA

Related Articles

  • Working with the AND Operator in Data Structures and Algorithms

    08/12/2024 | DSA

  • Generate All Valid Parentheses

    13/10/2024 | DSA

  • Minimum Cost to Connect Ropes Using Heap

    16/11/2024 | DSA

  • Word Search in a 2D Grid

    13/10/2024 | DSA

  • Implementation of Adjacency Matrix and Adjacency List in Graph Theory

    16/11/2024 | DSA

  • Understanding Merge Sort

    06/12/2024 | DSA

  • Kth Largest and Smallest Elements Using Heap

    16/11/2024 | DSA

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design