Skip to content
Programmingoneonone
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Learn everything about programming

HackerRank Day 20 Sorting 30 days of code solution

YASH PAL, 31 July 202413 October 2025

Hackerrank Day 20 Sorting problem solution – In this problem set, we need to develop a program that can accept an array as input and then sort those array elements, and then we need to print out that array.

Task
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 lines:

Array is sorted in numSwaps swaps.
where numSwaps is the number of swaps that took place.
First Element: firstElement
where firstElement is the first element in the sorted array.
Last Element: lastElement
where lastElement is the last element in the sorted array.

Hint: To complete this challenge, you will need to add a variable that keeps a running tally of all swaps that occur during execution.

Input Format

The first line contains an integer, n, the number of elements in array a.
The second line contains n space-separated integers that describe a[0],a[1],…,a[n-1].

Constraints
2 <= n <= 600
1<= a[i]<= 2 x 106, where 0 <= i <n.

Output Format

Print the following three lines of output:
Array is sorted in numSwaps swaps.
where numSwaps is the number of swaps that took place.
First Element: firstElement
where firstElement is the first element in the sorted array.
Last Element: lastElement
where lastElement is the last element in the sorted array.

Sorting problem solution in Python 2.

#!/bin/python

import sys


n = int(raw_input().strip())
a = map(int,raw_input().strip().split(' '))
totalSwaps = 0
for i in range(n):
    thisSwaps = 0
    for j in range(n-i-1):
        if a[j] > a[j+1]:
            a[j],a[j+1] = a[j+1],a[j]
            thisSwaps += 1
    totalSwaps += thisSwaps        
    if thisSwaps == 0:
        break
print "Array is sorted in {} swaps.".format(totalSwaps)
print "First Element: {}".format(a[0])
print "Last Element: {}".format(a[-1])
        

Problem solution in Python 3.

#!/bin/python3

import sys

n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
nofswap = 0
for i in range(0,n-1):
    for i in range(0,n-1):
        if a[i]>a[i+1]:
            a[i],a[i+1] = a[i+1],a[i]
            nofswap +=1

print("Array is sorted in", nofswap, "swaps.")
print("First Element:",a[0])
print("Last Element:",a[-1])

Problem solution in java.

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

public class Solution {

    public static int bubbleSort(int[] a, int n){
		int numSwaps = 0;
		for (int i = 0; i < n; i++) {
		    int numberOfSwaps = 0;
		    
		    for (int j = 0; j < n - 1; j++) {
		        if (a[j] > a[j + 1]) {
		            //swap(a[j], a[j + 1]);
		            
		        	int temp = a[j+1];
		    		a[j+1] = a[j];
		    		a[j] = temp;
		            
		            numberOfSwaps++;
		            numSwaps++;
		        }
		    }
		    
		    if (numberOfSwaps == 0) {
		        break;
		    }
		}
		return numSwaps;
	}
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = sc.nextInt();
		sc.close();
		
		int numSwaps = bubbleSort(a, n);
		
		System.out.println("Array is sorted in " + numSwaps + " swaps.");
		System.out.println("First Element: " + a[0]);
		System.out.println("Last Element: " + a[n-1]);
    }
}

Problem solution in C++.

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

    return 0;
}

Problem solution in C.

#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 total = 0;
    for (int i = 0; i < n; i++) {
        int s = 0;
        for (int j = 0; j < n-1; j++) {
            if (a[j] > a[j+1]) {
                int t = a[j];
                a[j] = a[j+1];
                a[j+1] = t;
                s++;
                total++;
            }
        }
        if (s == 0)
            break;
    }
    
    printf("Array is sorted in %d swaps.n", total);
    printf("First Element: %dn", a[0]);
    printf("Last Element: %dn", a[n-1]);
    
    return 0;
}

Problem solution in Javascript.

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 totalNum = 0
    for (var i = 0; i < a.length; i++) {
        var numberOfSwaps = 0
        for (var j = 0; j < a.length -1; j++) {
            if (a[j] > a[j + 1]) {
                var temp = a[j+1];
                a[j+1] = a[j];
                a[j] = temp;
                numberOfSwaps++;
            }
        }
        totalNum += numberOfSwaps;
        if (numberOfSwaps == 0) {
            break;
        }
    }
    console.log('Array is sorted in '+totalNum+ ' swaps.')
    console.log('First Element: '+a[0]);
    console.log('Last Element: '+a[a.length-1]);
}
30 days of code coding problems solutions HackerRank

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2025 Programmingoneonone | WordPress Theme by SuperbThemes