Day 20: Sorting In Java | 30 Days Of Code | Hackerrank Programming Solutions

Hello Programmers/Coders, Today we are going to share solutions of Programming problems of 30 Days Of Code, HackerRank. At Each Problem with Successful submission with all Test Cases Passed, you will get an score or marks. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for Day 20: Sorting in Java-HackerRank Problem. We are providing the correct and tested solutions of coding problems present on HackerRank. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

Link for the ProblemDay 20: Sorting – Hacker Rank Solution

Day 20: Sorting – Hacker Rank Solution

Problem:

Objective
Today, we’re discussing a simple sorting algorithm called Bubble Sort. Check out the Tutorial tab for learning materials and an instructional video!


Consider the following version of Bubble Sort:

for (int i = 0; i < n; i++) {
    // Track number of elements swapped during a single array traversal
    int numberOfSwaps = 0;
    
    for (int j = 0; j < n - 1; j++) {
        // Swap adjacent elements if they are in decreasing order
        if (a[j] > a[j + 1]) {
            swap(a[j], a[j + 1]);
            numberOfSwaps++;
        }
    }
    
    // If no elements were swapped during a traversal, array is sorted
    if (numberOfSwaps == 0) {
        break;
    }
}

Task
Given an array, , of size  distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following  lines:

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

original a: 4 3 1 2
round 1  a: 3 1 2 4 swaps this round: 3
round 2  a: 1 2 3 4 swaps this round: 2
round 3  a: 1 2 3 4 swaps this round: 0

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

Array is sorted in 5 swaps.
First Element: 1
Last Element: 4

Input Format

The first line contains an integer, , the number of elements in array .
The second line contains  space-separated integers that describe .

Constraints

  • , where .

Output Format

Print the following three lines of output:

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

Sample Input 0

3
1 2 3

Sample Output 0

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

Explanation 0

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

Sample Input 1

3
3 2 1

Sample Output 1

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

Explanation 1

The array  is not sorted, so we perform the following  swaps. Each line shows  after each single element is swapped.

After  swaps, the array is sorted.

Day 20: Sorting – Hacker Rank Solution
import java.util.Scanner;

/**
 * @author Techno-RJ
 *
 */
public class Day20Sorting {
	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();
		}
		in.close();
		int count = 0;
		boolean swapped = true;
		for (int j = a.length - 1; (j >= 0 && swapped); j--) {
			swapped = false;
			for (int k = 0; k < j; k++) {

				if (a[k] > a[k + 1]) {
					int temp = a[k];
					count++;
					a[k] = a[k + 1];
					a[k + 1] = temp;
					swapped = true;
				}
			}
		}
		System.out.println("Array is sorted in " + count + " swaps.");
		System.out.println("First Element: " + a[0]);
		System.out.println("Last Element: " + a[a.length - 1]);

	}
}

Leave a Comment

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker🙏.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock