In this HackerRank Sorting: Bubble Sort Interview preparation kit you have Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm.


HackerRank Sorting: Bubble Sort Interview preparation kit solution


Problem solution in Python programming.

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the countSwaps function below.
def countSwaps(a):
    swaps=0
    for i in range(len(a)):
        for j in range(len(a)-1):
            if a[j]> a[j+1]:
                a[j],a[j+1]=a[j+1],a[j]
                swaps+=1
    print("Array is sorted in " + str(swaps) + " swaps.")
    print("First Element: " + str(a[0]))
    print("Last Element: " + str(a[len(a)-1]))

if __name__ == '__main__':
    n = int(input())

    a = list(map(int, input().rstrip().split()))

    countSwaps(a)



Problem solution in Java Programming.

import static java.lang.Integer.parseInt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;

public class Day20_Sorting {

	static int MB = 1 << 20;
	static BufferedReader BR = new BufferedReader( new InputStreamReader(System.in, StandardCharsets.US_ASCII), 20 * MB);
	
	static StringTokenizer st;
	static String lastLine;
	
	static void newLine() throws IOException {
		lastLine = BR.readLine();
		st = new StringTokenizer(lastLine);
	}
	
	public static void main(String[] args) throws IOException {
		newLine();
		int N = parseInt(st.nextToken());
		
		newLine();
		int[] A = new int[N];
		for (int i = 0; i < N; i++) {
			A[i] = parseInt(st.nextToken());
		}

		int numberOfSwapps = bubbleSort(N, A);
		int firstElement = A[0];
		int lastElement = A[N-1];
		print(numberOfSwapps, firstElement, lastElement);
	}

	private static void print(int numberOfSwapps, int firstElement, int lastElement) {
		StringBuilder sb = new StringBuilder();
		
		sb.append("Array is sorted in ").append(numberOfSwapps).append(" swaps.\n");
		sb.append("First Element: ").append(firstElement).append('\n');
		sb.append("Last Element: ").append(lastElement).append('\n');
		
		System.out.print(sb);
	}

	private static int bubbleSort(int N, int[] A) {
		int cnt = 0;
		
		for (int i = 0; i < N; i++) {
		    // Track number of elements swapped during a single array traversal
		    int numberOfSwaps = 0;
		    
		    for (int j = 0; j < N - 1; j++) {
		        // Swap adjacent elements if they are in decreasing order
		        if (A[j] > A[j + 1]) {
		            swap(A, j , j + 1);
		            numberOfSwaps++;
		        }
		    }
		    cnt += numberOfSwaps;
		    
		    // If no elements were swapped during a traversal, array is sorted
		    if (numberOfSwaps == 0) {
		        break;
		    }
		}
		
		return cnt;
	}

	private static void swap(int[] a, int i, int j) {
		int tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}

}


Problem solution in C++ programming.

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;


int main(){
    int n,temp,c=0;
    cin >> n;
   int a[n];
    for(int i=0;i<n;i++)
        {
        cin>>a[i];
    }
    for(int i=0;i<n-1;i++)
    {
        for(int j=0;j<n-i-1;j++)
            {
            if(a[j]>a[j+1])
                {
                temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
                c++;
            }
        }
    
    if(c==0)
        {
        break;
    }}
    cout<<"Array is sorted in "<<c<<" swaps."<<endl;
    cout<<"First Element:"<<" "<<a[0]<<endl;
    cout<<"Last Element:"<<" "<<a[n-1]<<endl;
    return 0;
}


Problem solution in C programming.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n; 
    scanf("%d",&n);
    int *a = malloc(sizeof(int) * n);
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&a[a_i]);
    }
    
    int i,j,temp,k=0;
    for(i=0;i<n-1;i++){
        for(j=0;j<n-1-i;j++){
            if(a[j]>a[j+1]){
                temp =a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
                k++;
            }
        }
    }
    
    printf("Array is sorted in %d swaps.\n",k);
printf("First Element: %d\n",a[0]);
printf("Last Element: %d\n",a[n-1]);
    
    
    return 0;
}


Problem solution in JavaScript programming.

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var n = parseInt(readLine());
    a = readLine().split(' ');
    a = a.map(Number);
    tally = 0;
    
    for (var i = 0; i < n; i++) {

        
        for (var x = 0; x < n - 1; x++) {
            if (a[x] > a[x + 1]) {
                const temp = a[x + 1];
                a[x + 1] = a[x];
                a[x] = temp;
                tally++;
            }
        }
        
        if(tally === 0)
            break;
    }
   
    
    process.stdout.write('Array is sorted in ' + tally + ' swaps.' + '\n');
    process.stdout.write('First Element: ' + a[0] + '\n');
    process.stdout.write('Last Element: ' + a[n - 1]);
    
    

}