Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Heap sort for Linked List
Next article icon

Lexicographical ordering using Heap Sort

Last Updated : 02 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of strings. The task is to sort the array in lexicographical order using Heap Sort.
Examples: 
 

Input: arr[] = { “banana”, “apple”, “mango”, “pineapple”, “orange” } 
Output: apple banana mango orange pineapple
Input: arr[] = { “CAB”, “ACB”, “ABC”, “CBA”, “BAC” } 
Output: ABC, ACB, BAC, BCA, CAB, CBA 
 

 

Approach: The basic idea is to use Heap sort and here the min-heap is being used to print in the lexicographical order.
Below is the implementation of the approach: 
 

C++




// C++ implementation to print
// the string in Lexicographical order
#include <iostream>
#include <string>
using namespace std;
 
// Used for index in heap
int x = -1;
 
// Predefining the heap array
string heap[1000];
 
// Defining formation of the heap
void heapForm(string k)
{
    x++;
 
    heap[x] = k;
 
    int child = x;
 
    string tmp;
 
    int index = x / 2;
 
    // Iterative heapiFy
    while (index >= 0) {
 
        // Just swapping if the element
        // is smaller than already
        // stored element
        if (heap[index] > heap[child]) {
 
            // Swapping the current index
            // with its child
            tmp = heap[index];
            heap[index] = heap[child];
            heap[child] = tmp;
            child = index;
 
            // Moving upward in the
            // heap
            index = index / 2;
        }
        else {
            break;
        }
    }
}
 
// Defining heap sort
void heapSort()
{
    int left1, right1;
 
    while (x >= 0) {
        string k;
        k = heap[0];
 
        // Taking output of
        // the minimum element
        cout << k << " ";
 
        // Set first element
        // as a last one
        heap[0] = heap[x];
 
        // Decrement of the
        // size of the string
        x = x - 1;
 
        string tmp;
 
        int index = 0;
 
        int length = x;
 
        // Initializing the left
        // and right index
        left1 = 1;
 
        right1 = left1 + 1;
 
        while (left1 <= length) {
 
            // Process of heap sort
            // If root element is
            // minimum than its both
            // of the child then break
            if (heap[index] <= heap[left1]
                && heap[index] <= heap[right1]) {
                break;
            }
 
            // Otherwise checking that
            // the child which one is
            // smaller, swap them with
            // parent element
            else {
 
                // Swapping
                if (heap[left1] < heap[right1]) {
                    tmp = heap[index];
                    heap[index] = heap[left1];
                    heap[left1] = tmp;
                    index = left1;
                }
 
                else {
                    tmp = heap[index];
                    heap[index] = heap[right1];
                    heap[right1] = tmp;
                    index = right1;
                }
            }
 
            // Changing the left index
            // and right index
            left1 = 2 * left1;
            right1 = left1 + 1;
        }
    }
}
 
// Utility function
void sort(string k[], int n)
{
 
    // To heapiFy
    for (int i = 0; i < n; i++) {
        heapForm(k[i]);
    }
 
    // Calling heap sort function
    heapSort();
}
 
// Driver Code
int main()
{
    string arr[] = { "banana", "orange", "apple",
                   "pineapple", "berries", "litchi" };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    sort(arr, n);
}
 
 

Java




// Java implementation to print
// the string in Lexicographical order
class GFG
{
 
// Used for index in heap
static int x = -1;
 
// Predefining the heap array
static String []heap = new String[1000];
 
// Defining formation of the heap
static void heapForm(String k)
{
    x++;
 
    heap[x] = k;
 
    int child = x;
 
    String tmp;
 
    int index = x / 2;
 
    // Iterative heapiFy
    while (index >= 0)
    {
 
        // Just swapping if the element
        // is smaller than already
        // stored element
        if (heap[index].compareTo(heap[child]) > 0)
        {
 
            // Swapping the current index
            // with its child
            tmp = heap[index];
            heap[index] = heap[child];
            heap[child] = tmp;
            child = index;
 
            // Moving upward in the
            // heap
            index = index / 2;
        }
        else
        {
            break;
        }
    }
}
 
// Defining heap sort
static void heapSort()
{
    int left1, right1;
 
    while (x >= 0)
    {
        String k;
        k = heap[0];
 
        // Taking output of
        // the minimum element
        System.out.print(k + " ");
 
        // Set first element
        // as a last one
        heap[0] = heap[x];
 
        // Decrement of the
        // size of the string
        x = x - 1;
 
        String tmp;
 
        int index = 0;
 
        int length = x;
 
        // Initializing the left
        // and right index
        left1 = 1;
 
        right1 = left1 + 1;
 
        while (left1 <= length)
        {
 
            // Process of heap sort
            // If root element is
            // minimum than its both
            // of the child then break
            if (heap[index].compareTo(heap[left1]) <= 0 &&
                heap[index].compareTo(heap[right1]) <= 0)
            {
                break;
            }
 
            // Otherwise checking that
            // the child which one is
            // smaller, swap them with
            // parent element
            else
            {
 
                // Swapping
                if (heap[left1].compareTo(heap[right1])< 0)
                {
                    tmp = heap[index];
                    heap[index] = heap[left1];
                    heap[left1] = tmp;
                    index = left1;
                }
 
                else
                {
                    tmp = heap[index];
                    heap[index] = heap[right1];
                    heap[right1] = tmp;
                    index = right1;
                }
            }
 
            // Changing the left index
            // and right index
            left1 = 2 * left1;
            right1 = left1 + 1;
        }
    }
}
 
// Utility function
static void sort(String k[], int n)
{
 
    // To heapiFy
    for (int i = 0; i < n; i++)
    {
        heapForm(k[i]);
    }
 
    // Calling heap sort function
    heapSort();
}
 
// Driver Code
public static void main(String[] args)
{
    String arr[] = {"banana", "orange", "apple",
                    "pineapple", "berries", "lichi" };
 
    int n = arr.length;
 
    sort(arr, n);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 implementation to print
# the string in Lexicographical order
 
# Used for index in heap
x = -1;
 
# Predefining the heap array
heap = [0] * 1000;
 
# Defining formation of the heap
def heapForm(k):
    global x;
    x += 1;
 
    heap[x] = k;
 
    child = x;
 
    index = x // 2;
 
    # Iterative heapiFy
    while (index >= 0):
 
        # Just swapping if the element
        # is smaller than already
        # stored element
        if (heap[index] > heap[child]):
 
            # Swapping the current index
            # with its child
            tmp = heap[index];
            heap[index] = heap[child];
            heap[child] = tmp;
            child = index;
 
            # Moving upward in the
            # heap
            index = index // 2;
 
        else:
            break;
 
# Defining heap sort
def heapSort():
    global x;
    while (x >= 0):
        k = heap[0];
 
        # Taking output of
        # the minimum element
        print(k, end = " ");
 
        # Set first element
        # as a last one
        heap[0] = heap[x];
 
        # Decrement of the
        # size of the string
        x = x - 1;
 
        tmp = -1;
 
        index = 0;
 
        length = x;
 
        # Initializing the left
        # and right index
        left1 = 1;
 
        right1 = left1 + 1;
 
        while (left1 <= length):
 
            # Process of heap sort
            # If root element is
            # minimum than its both
            # of the child then break
            if (heap[index] <= heap[left1] and
                heap[index] <= heap[right1]):
                break;
 
            # Otherwise checking that
            # the child which one is
            # smaller, swap them with
            # parent element
            else:
 
                # Swapping
                if (heap[left1] < heap[right1]):
                    tmp = heap[index];
                    heap[index] = heap[left1];
                    heap[left1] = tmp;
                    index = left1;
 
                else:
                    tmp = heap[index];
                    heap[index] = heap[right1];
                    heap[right1] = tmp;
                    index = right1;
 
            # Changing the left index
            # and right index
            left1 = 2 * left1;
            right1 = left1 + 1;
 
# Utility function
def sort(k, n):
     
    # To heapiFy
    for i in range(n):
        heapForm(k[i]);
 
    # Calling heap sort function
    heapSort();
 
# Driver Code
if __name__ == '__main__':
    arr = ["banana", "orange", "apple",
           "pineapple", "berries", "lichi"];
 
    n = len(arr);
 
    sort(arr, n);
 
# This code is contributed by PrinciRaj1992
 
 

C#




// C# implementation to print
// the string in Lexicographical order
using System;
     
class GFG
{
 
// Used for index in heap
static int x = -1;
 
// Predefining the heap array
static String []heap = new String[1000];
 
// Defining formation of the heap
static void heapForm(String k)
{
    x++;
 
    heap[x] = k;
 
    int child = x;
 
    String tmp;
 
    int index = x / 2;
 
    // Iterative heapiFy
    while (index >= 0)
    {
 
        // Just swapping if the element
        // is smaller than already
        // stored element
        if (heap[index].CompareTo(heap[child]) > 0)
        {
 
            // Swapping the current index
            // with its child
            tmp = heap[index];
            heap[index] = heap[child];
            heap[child] = tmp;
            child = index;
 
            // Moving upward in the
            // heap
            index = index / 2;
        }
        else
        {
            break;
        }
    }
}
 
// Defining heap sort
static void heapSort()
{
    int left1, right1;
 
    while (x >= 0)
    {
        String k;
        k = heap[0];
 
        // Taking output of
        // the minimum element
        Console.Write(k + " ");
 
        // Set first element
        // as a last one
        heap[0] = heap[x];
 
        // Decrement of the
        // size of the string
        x = x - 1;
 
        String tmp;
 
        int index = 0;
 
        int length = x;
 
        // Initializing the left
        // and right index
        left1 = 1;
 
        right1 = left1 + 1;
 
        while (left1 <= length)
        {
 
            // Process of heap sort
            // If root element is
            // minimum than its both
            // of the child then break
            if (heap[index].CompareTo(heap[left1]) <= 0 &&
                heap[index].CompareTo(heap[right1]) <= 0)
            {
                break;
            }
 
            // Otherwise checking that the child
            // which one is smaller, swap them with
            // parent element
            else
            {
 
                // Swapping
                if (heap[left1].CompareTo(heap[right1]) < 0)
                {
                    tmp = heap[index];
                    heap[index] = heap[left1];
                    heap[left1] = tmp;
                    index = left1;
                }
 
                else
                {
                    tmp = heap[index];
                    heap[index] = heap[right1];
                    heap[right1] = tmp;
                    index = right1;
                }
            }
 
            // Changing the left index
            // and right index
            left1 = 2 * left1;
            right1 = left1 + 1;
        }
    }
}
 
// Utility function
static void sort(String []k, int n)
{
 
    // To heapiFy
    for (int i = 0; i < n; i++)
    {
        heapForm(k[i]);
    }
 
    // Calling heap sort function
    heapSort();
}
 
// Driver Code
public static void Main(String[] args)
{
    String []arr = {"banana", "orange", "apple",
                    "pineapple", "berries", "lichi" };
 
    int n = arr.Length;
 
    sort(arr, n);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




// JavaScript implementation to print
// the string in Lexicographical order
 
// Used for index in heap
let x = -1;
 
// Predefining the heap array
let heap = [];
 
// Defining formation of the heap
function heapForm(k) {
  x++;
 
  heap[x] = k;
  let child = x;
  let tmp;
  let index = Math.floor(x / 2);
 
  // Iterative heapiFy
  while (index >= 0) {
   
    // Just swapping if the element
    // is smaller than already
    // stored element
    if (heap[index] > heap[child])
    {
     
      // Swapping the current index
      // with its child
      tmp = heap[index];
      heap[index] = heap[child];
      heap[child] = tmp;
      child = index;
 
      // Moving upward in the
      // heap
      index = Math.floor(index / 2);
    } else {
      break;
    }
  }
}
 
// Defining heap sort
function heapSort() {
  let left1, right1;
 
  while (x >= 0) {
    let k;
    k = heap[0];
 
    // Taking output of
    // the minimum element
    console.log(k);
 
    // Set first element
    // as a last one
    heap[0] = heap[x];
 
    // Decrement of the
    // size of the string
    x = x - 1;
    let tmp;
    let index = 0;
    let length = x;
 
    // Initializing the left
    // and right index
    left1 = 1;
 
    right1 = left1 + 1;
 
    while (left1 <= length) {
      // Process of heap sort
      // If root element is
      // minimum than its both
      // of the child then break
      if (heap[index] <= heap[left1] && heap[index] <= heap[right1]) {
        break;
      }
 
      // Otherwise checking that
      // the child which one is
      // smaller, swap them with
      // parent element
      else {
        // Swapping
        if (heap[left1] < heap[right1]) {
          tmp = heap[index];
          heap[index] = heap[left1];
          heap[left1] = tmp;
          index = left1;
        } else {
          tmp = heap[index];
          heap[index] = heap[right1];
          heap[right1] = tmp;
          index = right1;
        }
      }
 
      // Changing the left index
      // and right index
      left1 = 2 * left1;
      right1 = left1 + 1;
    }
  }
}
 
// Utility function
function sort(arr) {
  // To heapiFy
  for (let i = 0; i < arr.length; i++) {
    heapForm(arr[i]);
  }
 
  // Calling heap sort function
  heapSort();
}
 
// Driver Code
let arr = ["banana", "orange", "apple", "pineapple", "berries", "litchi"];
 
sort(arr);
 
// This code is contributed by Satyam Nayak
 
 


Next Article
Heap sort for Linked List

K

kunalcodr
Improve
Article Tags :
  • Advanced Data Structure
  • Algorithms
  • C++
  • C++ Programs
  • DSA
  • Programming Language
  • Sorting
  • Strings
  • Heap Sort
Practice Tags :
  • CPP
  • Advanced Data Structure
  • Algorithms
  • Sorting
  • Strings

Similar Reads

  • Heap Sort - Data Structures and Algorithms Tutorials
    Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
    14 min read
  • Iterative HeapSort
    HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
    11 min read
  • Java Program for Heap Sort
    Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where first find the maximum element and place it at the end. We repeat the same process for the remaining element. Heap Sort in JavaBelow is the implementation of Heap Sort
    3 min read
  • C++ Program for Heap Sort
    Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Recommended PracticeHeap SortTry It!
    3 min read
  • sort_heap function in C++
    The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h
    3 min read
  • Heap Sort - Python
    Heapsort is a comparison-based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Heap Sort AlgorithmFirst convert the array i
    4 min read
  • Lexicographical ordering using Heap Sort
    Given an array arr[] of strings. The task is to sort the array in lexicographical order using Heap Sort.Examples: Input: arr[] = { "banana", "apple", "mango", "pineapple", "orange" } Output: apple banana mango orange pineappleInput: arr[] = { "CAB", "ACB", "ABC", "CBA", "BAC" } Output: ABC, ACB, BAC
    10 min read
  • Heap sort for Linked List
    Given a linked list, the task is to sort the linked list using HeapSort. Examples: Input: list = 7 -> 698147078 -> 1123629290 -> 1849873707 -> 1608878378 -> 140264035 -> -1206302000Output: -1206302000 -> 7 -> 140264035 -> 1123629290 -> 1608878378 -> 1698147078 ->1
    14 min read
  • Python Code for time Complexity plot of Heap Sort
    Prerequisite : HeapSort Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. We implement Heap Sort he
    3 min read
  • Sorting algorithm visualization : Heap Sort
    An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences