Day 20: Sorting | 30 Days of Coding | HackerRank | Java Language

**Before watching this make sure that you’ve tried enough**
Language: Java 7

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        int temp,count = 0;
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        // Write Your Code Here
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n - 1;j++){
                if(a[j] > a[j+1]){
                    temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                    count++;
                }
            }
        }
        
        System.out.println("Array is sorted in "+count+" swaps.");
        System.out.println("First Element: "+a[0]);
        System.out.println("Last Element: "+a[n-1]);
    }
}

 

If this solution helped you, please share this with your friends.
And if you have anything to say, let me know in the comment section.
More solutions are coming so Like our Facebook page and Subscribe to our YouTube channel to stay connected.

Leave a Comment