Hackerrank Day 20: In this problem we have to implement a sorting algorithm. Sorting is arranging of data based on some condition. Mostly data is arranged in ascending or descending order. We have lot of sorting techniques like quick sort , merge sort, bubble sort , insertion sort , selection sort etc.

We can use any sorting technique in this problem.

Lets find out the solution of : Day 20

**Task**

**Sample Input**

1 2 |
3 3 2 1 |

**Sample Output**

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

Solution to the problem is :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
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]; for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextInt(); } // Write Your Code Here int swapReturn= bubbleSort(a); System.out.format("Array is sorted in %d swaps.",swapReturn); System.out.println(); System.out.println("First Element: "+a[0]); System.out.println("Last Element: "+a[a.length-1]); } public static int bubbleSort(int arr[]) { int temp; int swap=0; for(int x=0; x<arr.length-1;x++) { for(int y=0;y<arr.length-x-1;y++) { if(arr[y]>arr[y+1]) { temp=arr[y]; arr[y]=arr[y+1]; arr[y+1]=temp; swap++; } } } return swap; } } |

Thanks for the visit checkout the day 21 tutorial as well.. đź™‚