learn kro favicon img

Day 20: Sorting | HackerRank Solution

Hello coders, today we are going to solve Day 20: Sorting HackerRank Solution in C++Java and Python.

Objective

Today, we’re discussing a simple sorting algorithm called Bubble Sort.

Consider the following version of Bubble Sort:

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

  1. Array is sorted in numSwaps swaps.
    where numSwaps is the number of swaps that took place.
  2. First Element: firstElement
    where firstElement is the first element in the sorted array.
  3. 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.

Example
a = [4, 3, 1, 2]

In the first round, the 4 is swapped at each of the 3 comparisons, ending in the last position. In the second round, the 3 is swapped at 2 of the 3 comparisons. Finally, in the third round, no swaps are made so the iterations stop. The output is the following:

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 x106where 0 <= i < n

Output Format

Print the following three lines of output:

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

Sample Input 0

Sample Output 0

Explanation 0

The array is already sorted, so 0 swaps take place and we print the necessary 3 lines of output shown above.

Sample Input 1

Sample Output 1

Explanation 1

The array a = [3, 2, 1] is not sorted, so we perform the following 3 swaps. Each line shows a after each single element is swapped.

  1. [3, 2, 1] = [2, 3, 1]
  2. [2, 3, 1] = [2, 1, 3]
  3. [2, 1, 3] = [1 , 2, 3]

After 3 swaps, the array is sorted.

Solution – Day 20: Sorting

C++

Java

Python

Disclaimer: The above Problem (Day 20: Sorting) is generated by Hacker Rank but the Solution in Provided by Learnkro. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *