COURSES
MBAData Science & AnalyticsDoctorate Software & Tech AI | ML MarketingManagement
Professional Certificate Programme in HR Management and AnalyticsPost Graduate Certificate in Product ManagementExecutive Post Graduate Program in Healthcare ManagementExecutive PG Programme in Human Resource ManagementMBA in International Finance (integrated with ACCA, UK)Global Master Certificate in Integrated Supply Chain ManagementAdvanced General Management ProgramManagement EssentialsLeadership and Management in New Age BusinessProduct Management Online Certificate ProgramStrategic Human Resources Leadership Cornell Certificate ProgramHuman Resources Management Certificate Program for Indian ExecutivesGlobal Professional Certificate in Effective Leadership and ManagementCSM® Certification TrainingCSPO® Certification TrainingLeading SAFe® 5.1 Training (SAFe® Agilist Certification)SAFe® 5.1 POPM CertificationSAFe® 5.1 Scrum Master Certification (SSM)Implementing SAFe® 5.1 with SPC CertificationSAFe® 5 Release Train Engineer (RTE) CertificationPMP® Certification TrainingPRINCE2® Foundation and Practitioner Certification
Law
Job Linked
Bootcamps
Study Abroad
Master in International Management (120 ECTS)MS in Data AnalyticsMS in Project ManagementMS in Information TechnologyMasters Degree in Data Analytics and VisualizationMasters Degree in Artificial IntelligenceMBS in Entrepreneurship and MarketingMSc in Data AnalyticsMS in Data AnalyticsMS in Computer ScienceMaster of Science in Business AnalyticsMaster of Business Administration MS in Data ScienceMS in Information TechnologyMaster of Business AdministrationMS in Applied Data ScienceMaster of Business Administration | STEMMS in Data AnalyticsM.Sc. Data Science (60 ECTS)Master of Business AdministrationMS in Information Technology and Administrative Management MS in Computer Science Master of Business Administration MBA General Management-90 ECTSMSc International Business ManagementMS Data Science Master of Business Administration MSc Business Intelligence and Data ScienceMS Data Analytics MS in Management Information SystemsMSc International Business and ManagementMS Engineering ManagementMS in Machine Learning EngineeringMS in Engineering ManagementMSc Data EngineeringMSc Artificial Intelligence EngineeringMPS in InformaticsMPS in Applied Machine IntelligenceMS in Project ManagementMPS in AnalyticsMS in Project ManagementMS in Organizational LeadershipMPS in Analytics - NEU CanadaMBA with specializationMPS in Informatics - NEU Canada Master in Business AdministrationMS in Digital Marketing and MediaMSc Sustainable Tourism and Event ManagementMSc in Circular Economy and Sustainable InnovationMSc in Impact Finance and Fintech ManagementMS Computer ScienceMS in Applied StatisticsMaster in Computer Information SystemsMBA in Technology, Innovation and EntrepreneurshipMSc Data Science with Work PlacementMSc Global Business Management with Work Placement MBA with Work PlacementMS in Robotics and Autonomous SystemsMS in Civil EngineeringMS in Internet of ThingsMSc International Logistics and Supply Chain ManagementMBA- Business InformaticsMSc International ManagementMBA in Strategic Data Driven ManagementMSc Digital MarketingMBA Business and MarketingMaster of Business AdministrationMSc in Sustainable Global Supply Chain ManagementMSc Digital Business Analytics MSc in International HospitalityMSc Luxury and Innovation ManagementMaster of Business Administration-International Business ManagementMS in Computer EngineeringMS in Industrial and Systems EngineeringMSc International Business ManagementMaster in ManagementMSc MarketingMSc Business ManagementMSc Global Supply Chain ManagementMS in Information Systems and Technology with Business Intelligence and Analytics ConcentrationMSc Corporate FinanceMSc Data Analytics for BusinessMaster of Business AdministrationMaster of Business AdministrationMaster of Business AdministrationMSc in International FinanceMSc in International Management and Global LeadershipMaster of Business AdministrationBachelor of BusinessMaster of Business Administration 60 ECTSMaster of Business Administration 90 ECTSMaster of Business Administration 90 ECTSBachelor of Business AnalyticsBachelor of Information TechnologyMaster of Business AdministrationMBA Business AnalyticsMSc in Marketing Analytics and Data IntelligenceMS Biotechnology Management and EntrepreneurshipMSc in Luxury and Fashion ManagementMaster of Business Administration (90 ECTS)Bachelor of Business Administration (180 ECTS)bca-v5-software-upgrad-pp
For College Students

Bubble Sort Code in Data Structure

$$/$$

In the video below, Aishwarya Rai will walk you through the Java implementation of Bubble sort code based on the pseudocode discussed earlier. Let's get going. Please download the following java file for your reference.

$$/$$

Video Transcript:

 

Now let us take a look at a simple implementation of bubble sort. For that we have defined a bubble sort function which takes in an input array called numbers. So here I am declaring a variable int n which equals to numbers dot length. And I am running two for loops nested one inside each other. This for loop runs I from zero till and this inner for loop starts j from one and goes till numbers dot length minus i. Now I'm comparing all the adjacent j elements. That is if numbers of j is less than numbers of j minus one, then what I do, I swap the elements located at j minus one and j. For that I have also defined a swap function here. What the swap function does is that it takes in two numbers I and j and an array. First it stores the value of array of I in a temporary variable temp. Then I overwrite my array of I with array of j. And finally the value which I had stored in temp is getting stored now in array of j. So in this way I was able to exchange the values in I and j. So after running

 

these two for loops, I simply return my output array which will now consist of my final sorted array. Let us now run this code and see.

 

So here you have seen that I was given this particular array and I called my bubble sort function on this array. So here the array is unsorted. And take a look here on the output console here all the elements are in the sorted order. So our bubble sort works perfectly.

 

Transcript Summary:

 

  • Bubble sort is a simple sorting algorithm used to sort an array of elements in ascending or descending order.

  • It works by repeatedly swapping adjacent elements if they are in the wrong order until the entire array is sorted.

  • The implementation of bubble sort involves defining a function that takes an input array called 'numbers'.

  • The function uses two nested for loops to compare adjacent elements of the array and swap them if they are not in the correct order.

  • A 'swap' function is also defined to facilitate the swapping of elements.

  • After running the two for loops, the sorted array is returned as output.

  • The bubble sort algorithm is demonstrated with an example array and is shown to work correctly.

 

Here is a question for you.

Don't you think that for each inner loop iteration if the number of swaps at any stage is 0, then we can say that the sequence is sorted and we do not need to move any further? Coming out of the loop at such a point can reduce the number of redundant steps in the code and hence the code can be optimised. For each inner loop iteration, you can check for the number of swaps at any step and compare it with 0. If the number of swaps at any step is 0, then you know the sequence is sorted now and there should be no computation further. This logic helps to optimize the bubble sort algorithm time complexity. Please look into the code below.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter the no. of elements :");
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int i = 0;
        int[] arr = new int[n];
        System.out.println("Enter the elements of the array :");
        for (i = 0; i < n; i++) {
            arr[i] = input.nextInt();
        }
        for (i = 0; i < n; i++) {
            // setting the initial value of swap to zero.
            int swap = 0;
            for (int j = 1; j < n - i; j++) {
                if (arr[j - 1] > arr[j]) {
                    //swapping when element at position j-1 is greater than element at j position.
                    int temp = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = temp;
                    swap = 1;
                    /* if at any step the swapping is done, we change the swap value to one,
                    so that we know  that the sequence is not sorted at this step.*/
                }
            }
            /*This will check if the swap value is not changed to 1, because if the value
            is not updated then it has not entered the inner loop even once, and no swapping was done.
            Therefore the sequence is sorted now.*/
            if (swap == 0) {
                    break;
                }
        }
        
        System.out.println("sorted array ");
        for (i = 0; i < n; i++) {
            System.out.println(arr[i]);
        }
    }
}

 

Awesome! You are done with the bubble sort code as well. But until now, all you’ve learnt is how this sorting works. The question  “How efficient is it” still remains unanswered. Let’s move on to the next video where you will find the answer to this question.