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:
Sort an array using Bubble Sort without using loops
Next article icon

Sorting Strings using Bubble Sort

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array.

In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The larger values sink to the bottom and are hence called sinking sort. At the end of each pass, smaller values gradually “bubble” their way upward to the top and hence called bubble sort.

 After all the passes, we get all the strings in sorted order.

Let us look at the code snippet

C++




// C++ implementation
 
#include <bits/stdc++.h>
using namespace std;
#define MAX 100
 
void sortStrings(char arr[][MAX], int n)
{
    char temp[MAX];
 
    // Sorting strings using bubble sort
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - 1 - i; j++) {
            if (strcmp(arr[j], arr[j + 1]) > 0) {
                strcpy(temp, arr[j]);
                strcpy(arr[j], arr[j + 1]);
                strcpy(arr[j + 1], temp);
            }
        }
    }
}
 
int main()
{
    char arr[][MAX] = { "GeeksforGeeks", "Quiz", "Practice",
                        "Gblogs", "Coding" };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    sortStrings(arr, n);
 
    printf("Strings in sorted order are : ");
    for (int i = 0; i < n; i++)
        printf("\n String %d is %s", i + 1, arr[i]);
    return 0;
}
 
 

Java




// Java implementation
class GFG {
 
    static int MAX = 100;
 
    public static void sortStrings(String[] arr, int n)
    {
        String temp;
 
        // Sorting strings using bubble sort
        for (int j = 0; j < n - 1; j++) {
            for (int i = j + 1; i < n; i++) {
                if (arr[j].compareTo(arr[i]) > 0) {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String[] arr = { "GeeksforGeeks", "Quiz",
                         "Practice", "Gblogs", "Coding" };
        int n = arr.length;
        sortStrings(arr, n);
        System.out.println(
            "Strings in sorted order are : ");
        for (int i = 0; i < n; i++)
            System.out.println("String " + (i + 1) + " is "
                               + arr[i]);
    }
}
 
// This code is contributed by
// sanjeev2552
 
 

C#




// C# implementation
using System;
 
class GFG {
    static int MAX = 100;
 
    public static void sortStrings(String[] arr, int n)
    {
        String temp;
 
        // Sorting strings using bubble sort
        for (int j = 0; j < n - 1; j++) {
            for (int i = j + 1; i < n; i++) {
                if (arr[j].CompareTo(arr[i]) > 0) {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String[] arr = { "GeeksforGeeks", "Quiz",
                         "Practice", "Gblogs", "Coding" };
        int n = arr.Length;
        sortStrings(arr, n);
        Console.WriteLine("Strings in sorted order are : ");
        for (int i = 0; i < n; i++)
            Console.WriteLine("String " + (i + 1) + " is "
                              + arr[i]);
    }
}
 
// This code is contributed by Princi Singh
 
 

Python3




# Python Implementation
 
 
def compare(a, b):
    return ((a < b) - (a > b))
 
 
def sort_string(arr, n):
    temp = ""
 
    # Sort string using the bubble sort
    for i in range(n-1):
        for j in range(i+1, n):
            if compare(arr[j], arr[i]) > 0:
                temp = arr[j]
                arr[j] = arr[i]
                arr[i] = temp
    print("String in sorted order are: ")
    for i in range(n):
        print(f'Strings {i + 1} is {arr[i]}')
 
 
# Driver code
arr = ["GeeksforGeeks", "Quiz", "Practice", "Gblogs", "Coding"]
n = len(arr)
sort_string(arr, n)
 
 
# This code is contributed by Prince Kumar
 
 

Javascript




// JavaScript implementation
function sortStrings(arr) {
    let temp;
 
    // Sorting strings using bubble sort
    for (let j = 0; j < arr.length - 1; j++) {
        for (let i = j + 1; i < arr.length; i++) {
            if (arr[j].localeCompare(arr[i]) > 0) {
                temp = arr[j];
                arr[j] = arr[i];
                arr[i] = temp;
            }
        }
    }
}
 
// Driver code
let arr = ["GeeksforGeeks", "Quiz", "Practice", "Gblogs", "Coding"];
sortStrings(arr);
console.log("Strings in sorted order are : ");
for (let i = 0; i < arr.length; i++) {
      console.log(`String ${i + 1} is ${arr[i]}`);
}
 
// This code is contributed by lokeshmvs21.
 
 
Output
Strings in sorted order are :   String 1 is Coding  String 2 is Gblogs  String 3 is GeeksforGeeks  String 4 is Practice  String 5 is Quiz

Time Complexity: O(n2) 
Auxiliary Space: O(MAX) or O(100) 

 



Next Article
Sort an array using Bubble Sort without using loops

R

Rahul Agrawal
Improve
Article Tags :
  • DSA
  • Sorting
Practice Tags :
  • Sorting

Similar Reads

  • Bubble Sort Algorithm
    Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
    8 min read
  • Recursive Bubble Sort
    Background : Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Example: First Pass: ( 5 1 4 2 8 ) --> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) --> ( 1 4
    10 min read
  • Time and Space Complexity Analysis of Bubble Sort
    The time complexity of Bubble Sort is O(n^2) in the worst-case scenario and the space complexity of Bubble sort is O(1). Bubble Sort only needs a constant amount of additional space during the sorting process. Complexity TypeComplexityTime ComplexityBest: O(n)Average: O(n^2)Worst: O(n^2)Space Comple
    3 min read
  • Bubble Sort in different languages

    • sin() in C
      The sin() function in C is a standard library function to find the sine value of the radian angle. It is used to evaluate the trigonometric sine function of an angle. It takes the radian angle as input and returns the sin of that angle. It is defined inside <math.h> header file. Syntax of sin(
      1 min read

    • Bubble Sort in C++
      Bubble Sort Algorithm is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. It is often used to introduce the concept of a sorting and is particularly suitable for sorting small datasets. In this article, we will learn how to implem
      4 min read

    • C++ Program for Recursive Bubble Sort
      Background: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Following is the iterative Bubble sort algorithm : // Iterative Bubble Sort bubbleSort(arr[], n) { for (i = 0; i n-1; i++) // Last i elements are already
      2 min read

    • Bubble Sort - Python
      Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Bubble Sort algorithm, sorts an array by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The algorithm iterates through the a
      2 min read

    • Bubble Sort algorithm using JavaScript
      Bubble sort algorithm is an algorithm that sorts an array by comparing two adjacent elements and swapping them if they are not in the intended order. Here order can be anything like increasing or decreasing. How Bubble-sort works?We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ], and the task is
      4 min read

    • p5.js | Bubble Sort
      Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. In order to know more about it. Please refer Bubble Sort Approach: Create an array of random values and render a bar corresponding to that value in terms of height. C
      2 min read

    • Sorting an array in Bash using Bubble sort
      Prerequisite: Bubble Sort Given an array arr sort the array in ascending order using bash scripting. Examples: Input : 9 7 2 5 Output : Array in sorted order : 2 5 7 9 Approach : For sorting the array bubble sort is the simplest technique. Bubble sort works by swapping the adjacent elements if they
      2 min read

    Visualization of Bubble Sort

    • Sorting Algorithms Visualization : Bubble Sort
      The human brain can easily process visuals in spite of long codes to understand the algorithms. In this article, Bubble sort visualization has been implemented using graphics.h library. As we all know that bubble sort swaps the adjacent elements if they are unsorted and finally the larger one being
      5 min read

    • Visualizing Bubble sort using Python
      Prerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go.
      3 min read

    • Bubble Sort Visualization using JavaScript
      GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Bubble Sort using JavaScript. We will see how the elements are swapped in Bubble Sort and how we get the final sorted array. We will also visualize the time complexity of Bubble Sort.  Refer
      4 min read

    • Bubble sort visualizer using PyGame
      In this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum
      3 min read

    • Visualizing Bubble Sort using Tkinter in Python
      In this article, we will use the Python GUI Library Tkinter to visualize the Bubble Sort algorithm.  Tkinter is a very easy to use and beginner-friendly GUI library that can be used to visualize the sorting algorithms.Here Bubble Sort Algorithm is visualized which works by repeatedly swapping the ad
      5 min read

  • Bubble Sort for Linked List by Swapping nodes
    Given a singly linked list, sort it using bubble sort by swapping nodes. Examples: Input: 5 -> 1 -> 32 -> 10 -> 78Output: 1 -> 5 -> 10 -> 32 -> 78 Input: 20 -> 4 -> 3Output: 3 -> 4 -> 20 Approach: To apply Bubble Sort to a linked list, we need to traverse the list
    10 min read
  • Sorting Strings using Bubble Sort
    Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array. In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The larger values sink to the bottom and are hence called sinking sort. At the end of each pa
    4 min read
  • Sort an array using Bubble Sort without using loops
    Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based o
    9 min read
  • Bubble Sort On Doubly Linked List
    Given a doubly linked list, the task is to sort the linked list in non-decreasing order by using bubble sort. Examples: Input : head: 5<->3<->4<->1<->2Output : head: 1<->2<->3<->4<->5 Input : head: 5<->4<->3<->2Output : head: 2<-
    15+ min read
  • Bubble sort using two Stacks
    Prerequisite : Bubble Sort Write a function that sort an array of integers using stacks and also uses bubble sort paradigm. Algorithm: 1. Push all elements of array in 1st stack 2. Run a loop for 'n' times(n is size of array) having the following : 2.a. Keep on pushing elements in the 2nd stack till
    6 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