In this HackerRank Day 20: Interfaces problem solution Given an array, a, of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following 3 lines:
  1. Array is sorted in numSwaps swaps.
  2. where numSwaps is the number of swaps that took place.
  3. First Element: firstElement
  4. where firstElement is the first element in the sorted array.
  5. Last Element: lastElement
  6. where lastElement is the last element in the sorted array.

HackerRank Day 20: Sorting problem solution

Problem solution in Python programming.

#!/bin/python3

import sys


n = int(input().strip())
a = [int(a_temp) for a_temp in input().strip().split(' ')]

def bubble_sort(array):
    num_swaps = 0
    for i in range(len(array)):
        for j in range(len(array)-1):
            if array[j] > array[j+1]:
                array[j],array[j+1] = array[j+1],array[j]
                num_swaps += 1
        if num_swaps == 0:
            break
    print("Array is sorted in "+str(num_swaps)+" swaps.")
    print("First Element: "+str(array[0]))
    print("Last Element: "+str(array[len(array)-1]))

bubble_sort(a)



Problem solution in Java programming.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        
        int numberOfSwaps = 0;
        for (int i = 0; i < n; i++) {
    
            for (int j = 0; j < n - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                    numberOfSwaps++;
                }
            }
    
            if (numberOfSwaps == 0) {
                break;
            }
        }
        
        System.out.println("Array is sorted in " + numberOfSwaps +  " swaps.");
        System.out.println("First Element: " + a[0]);
        System.out.println("Last Element: " + a[a.length-1]);
    }
}




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;

void swap(int& x, int& y){
    int temp = x;
    x = y;
    y = temp;
}

int main(){
    int n;
    cin >> n;
    vector<int> a(n);
    for(int a_i = 0;a_i < n;a_i++){
       cin >> a[a_i];
    }
    int numberOfSwaps;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n - 1; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
                numberOfSwaps++;
            }
        }
    }
    cout<<"Array is sorted in "<<numberOfSwaps<<" swaps.\n";
    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>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(){
    int n, swap_count = 0;
    scanf("%d", &n);
    int *a = (int *) malloc(sizeof(int) * n);
    for (int a_i = 0; a_i < n; a_i++) {
        scanf("%d", &a[a_i]);
    }

    for (int i = 0; i < n; i++) {
        int local_swap_count = 0;
        for (int j = 0; j < n - 1; j++) {
            if (a[j] > a[j + 1]) {
                swap(a+j, a+j+1);
                local_swap_count++;
            }
        }

        if (local_swap_count == 0) {
            break;
        }
        swap_count += local_swap_count;
    }
    printf("Array is sorted in %d swaps.\n", swap_count);
    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);
    
    var totalSwaps = 0;
    for (var i = 0; i < n; i++) {
        var numberOfSwaps = 0;
    
        for (var j = 0; j < n - 1; j++) {
            if (a[j] > a[j + 1]) {
                var left = a[j];
                a[j] = a[j + 1];
                a[j + 1] = left;
                numberOfSwaps++;
            }
        }
        
        if (numberOfSwaps == 0) {
            break;
        }
        totalSwaps += numberOfSwaps;
    }
    output(totalSwaps, a);
}

function output(numSwaps, sortedArray) {
    process.stdout.write("Array is sorted in " + numSwaps + " swaps.\n");
    process.stdout.write("First Element: " + sortedArray[0] + "\n");
    process.stdout.write("Last Element: " + sortedArray[sortedArray.length-1]);
}