HackerRank Day 20 Solution in Python: Sorting

Today we will see the HackerRank Day 20 Solution in Python. The problem is named Sorting, part of 30 Days of code on HackerRank. Let’s get started!

Day 20: Sorting Problem statement

We are given an array of size n with distinct elements, our task is to sort the array in ascending order using the Bubble Sort algorithm. Once sorted, we have to print the number of swaps required to sort the array, the first element of the sorted array, and the last element of the sorted array.

Sample Input

3
3 2 1

Sample Output

Array is sorted in 3 swaps.
First Element: 1
Last Element: 3

Explanation: The array is not sorted, so we perform 3 swaps to sort the array. After swapping 1 and 3 are the first and last element

You can solve the problem here.

HackerRank Day 20 Solution in Python

#!/bin/python3

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    #Get number of array elements
    n = int(input().strip())
    #get array elements
    a = list(map(int, input().rstrip().split()))
    
    #Variable to store count of swaps
    swap_count = 0
    
    #Iterate through the array n times
    for i in range(n):
        for j in range(i+1,n):
            if a[i]>a[j]:
                a[i],a[j] = a[j],a[i]
                swap_count+=1
                
    print("Array is sorted in {} swaps.".format(swap_count))
    print("First Element: {}".format(a[0]))
    print("Last Element: {}".format(a[-1]))

Code Explanation

  • First, we created a variable swap_count to store the count of swaps
  • Then, we iterate through the loop to compare elements and swap in the ascending order
  • If the element is swapped the swap_count variable is incremented by 1
  • Then print the number of swaps required to sort the array, the first element of the sorted array, and the last element of the sorted array.

Also Read:

Share:

Author: Ayush Purawr