Posts

Showing posts with the label day 20 sorting solution

Day 20: Sorting - HackerRank 30 days of code solution

Objective Today, we're discussing a simple sorting algorithm called  Bubble Sort . 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: Array is sorted in numSwaps swaps. where   is the number ...