Skip to main content

Bubble Sort

1. You are given an array(arr) of integers.

2. You have to sort the given array in increasing order using bubble sort.

Input Format

An Integer n 

arr1

arr2..

n integers

Output Format

Check the sample ouput and question video.


Constraints

1 <= N <= 10000

-10^9 <= arr[i] <= 10^9

Sample Input

5

-2 

3

Sample Output

Comparing -2 and 7

Swapping -2 and 7

Comparing 4 and 7

Swapping 4 and 7

Comparing 1 and 7

Swapping 1 and 7

Comparing 3 and 7

Swapping 3 and 7

Comparing 4 and -2

Comparing 1 and 4

Swapping 1 and 4

Comparing 3 and 4

Swapping 3 and 4

Comparing 1 and -2

Comparing 3 and 1

Comparing 1 and -2

-2

1

3

4

7


Solution:

import java.io.*;
import java.util.*;

public class Main {

  public static void bubbleSort(int[] arr) {
    //write your code here
    for(int i=0;i<arr.length;i++){
        for(int j=1;j<arr.length-i;j++)
            if(isSmaller(arr,j,j-1)){
                swap(arr,j,j-1);
            }
    }
  }

  // used for swapping ith and jth elements of array
  public static void swap(int[] arr, int i, int j) {
    System.out.println("Swapping " + arr[i] + " and " + arr[j]);
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }

  // return true if ith element is smaller than jth element
  public static boolean isSmaller(int[] arr, int i, int j) {
    System.out.println("Comparing " + arr[i] + " and " + arr[j]);
    if (arr[i] < arr[j]) {
      return true;
    } else {
      return false;
    }
  }

  public static void print(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
  }

  public static void main(String[] args) throws Exception {
    Scanner scn = new Scanner(System.in);
    int n = scn.nextInt();
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
      arr[i] = scn.nextInt();
    }
    bubbleSort(arr);
    print(arr);
  }

}

Comments

Must Read:

Data Formats ( XML & JSON ) XML AND JSON | Generate XSD for Persons

  Generate XSD for Persons Generate XSD for the following XML. XYZ organization wants to store the details of persons in an xml file. The following scenario helps in designing the XML document. Here PersonList  is the root tag. PersonList contains the entry of each person with adhaarno, name, age and address. <?xml version="1.0"  encoding="UTF-8"?> <PersonList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="PersonList.xsd">     <Person>         <adhaarno>414356782345</adhaarno>         <name>             <firstname>Zeenath</firstname>         </name>         <age>28</age>         <address>             <doorno...

DFA Solutions

  Question  1 Correct Mark 1.00 out of 1.00 Flag question Question text To secure the http messages in the API calls, its necessary to: Select one: a. All the above b. Use cryptography c. implement identity management d. avoid hardcoding any sensitive data in the messages Feedback The correct answer is: All the above Question  2 Correct Mark 1.00 out of 1.00 Remove flag Question text A team has completed 10 Sprints and moving to the 11th Sprint. Till Sprint 10, the team has achieved an average of 50 story points per sprint. The same is projected as their velocity for the upcoming sprints with the Client. What is this approach called? Select one: a. Velocity Driven Sprint Planning b. Velocity Driven Commitment c. Commitment Driven Velocity d. Commitment Driven Sprint Planning Feedback The correct answer is: Velocity Driven Sprint Planning Question  3 Incorrect Mark 0.00 out of 1.00 Remove flag Question text Jack is grooming himself to be a potential Product Owner. Kno...

Programming using Java Running case study - Requirement 1 / 6 | State Board of Cricket Council –V1.0 *

  State Board of Cricket Council –V1.0 * State Board of Cricket Council   State Board of Cricket Council (SBCC) is one of the leading cricket selection academies in the state . They are in need of an automated system that should manipulate the player details provided and also find the players who have secured star rating between a specific range from the database. You being their software consultant have been approached to develop a pilot java application which can be used by the  admin for the above mentioned requirement . UserInterface.java package  com.sbcc.main; import  com.sbcc.model.*; import  java.util.*; import  java.lang.*; import  com.sbcc.skeletonvalidator.SkeletonValidator; public   class   UserInterface  {      public   static   Player   pl ;      public   static   void   main ( String []  args ) {        ...

Data Formats ( XML & JSON ) XML AND JSON | Generate XSD for Students

  Generate XSD for Students   Generate XSD for the following XML. XYZ School wants to store the details of students in an xml file. The following scenario helps in designing the XML document. Here StudentList  is the root tag. StudentList contains the entry of each student with rollno, name, age, address and department. <?xml version="1.0" encoding="UTF-8"?> <StudentList  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="StudentList.xsd">     <Student rollno="2017CSE0055">         <name>             <firstname>Savitha</firstname>         </name>         <age>20</age>         <address>             <doorno>35</doorno>     ...

RDBMS Data Definition Language | Create Buses table

 efer the below schema and create the buses table. Column Name Datatype Size Constraint Constraint name Bus_no Number 11 Primary key PK_BUSES Bus_name Varchar2 20   Type Varchar2 20   Total_seats Number 11   Avail_seats Number 11     Result Description Summary of tests +------------------------------+ | 3 tests run / 3 test passed | +------------------------------+

Programming using Java Hands On - Control Structures | Celcius to Farenheit Conversion

  Celcius to Farenheit Conversion Write a program to convert  Celsius to Farenheit.  Display the result correct to 1 decimal. Create a class "CelsiusConversion.java" and write the main method. Hint : 5 * (F – 32) = 9 * C,   F-Farenheit , C- Celsius   Sample Input  1 : 80 Sample Output  1 : 176.0 Sample Input  2 : 88 Sample Output  2 : 190.4 Result Description Summary of tests *Note: All the test cases might not have same weightage +------------------------------+ | 7 tests run/ 7 tests passed | +------------------------------+

Count A+b+c+ Subsequences

 1. You are given a string str. 2. You are required to calculate and print the count of subsequences of the nature a+b+c+. For abbc -> there are 3 subsequences. abc, abc, abbc For abcabc -> there are 7 subsequences. abc, abc, abbc, aabc, abcc, abc, abc. Input Format A string str Output Format count of subsequences of the nature a+b+c+ Constraints 0 < str.length <= 10 Sample Input abcabc Sample Output 7 Solution: import java.io.*; import java.util.*; public class Main {     public static void main(String[] args) throws Exception {         Scanner sc = new Scanner(System.in);         String str = sc.nextLine();         int counta = 0, countb = 0, countc = 0;         for(int i=0;i<str.length();i++){             char ch = str.charAt(i);             if(ch == 'a')                 ++coun...

Data Formats ( XML & JSON ) XML AND JSON | Generate XSD For Breakfast Menu

  Generate XSD For Breakfast Menu Generate XSD for the given XML document <?xml version="1.0" encoding="UTF-8"?> <breakfast_menu> <food> <name>Turfle waffles</name> <price>$5.95</price> <description>This two turfle which has 2 famous product  is with real choco and maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name> <price>$24.6</price> <description>Light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> <food> <name>Berry-Berry Belgian Waffles</name> <price>$4.78</price> <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> <calories>400</calories> </food> <food> <name>Fried Toast</name> <pr...

Accenture Mock Quiz | Part 5

Question  40 Correct Marked out of 1.00 Flag question Question text Which of the following attribute is used by a HTML tag to apply inline style? Choose most appropriate option. Select one: a.  style   b.  id c.  styleclass d.  class Feedback The correct answer is: style Question  41 Correct Marked out of 1.00 Flag question Question text Identify the CORRECT statements with respect to CSS. a) CSS is used for giving style for HTML content b) External style sheet can be used only for one HTML page in a website Choose most appropriate option. Select one: a.  only a   b.  only b c.  neither a nor b d.  both a and b Feedback The correct answer is: only a Question  42 Correct Marked out of 1.00 Flag question Question text Which of the following statements is TRUE for CSS? A. An external style sheet is ideal when the style is applied to many pages B. An inline style created for a html tag can be reused for other tags in same page...

Subscribe to Get's Answer by Email