Header Ad

HackerRank Day 20 Sorting 30 days of code solution

In this HackerRank Day 20 Sorting 30 days of code 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.


Day 20 Sorting 30 days of code solution HackerRank


Problem solution in Python 2 programming.

#!/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 programming.

#!/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 programming.

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++ 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;
    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 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 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: %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 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]);
}

Post a Comment

0 Comments