Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Sorting: Bubble Sort

Consider the following version of Bubble Sort:

for (int i = 0; i < n; i++) {
    
    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]);
        }
    }
    
}

Task Given an n-element array, A=a[0],a[1],...,a[n-1] of distinct elements, sort array A in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three 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 must add a variable that keeps a running tally of all swaps that occur during execution.

Input Format

The first line contains an integer, n, denoting the number of elements in array A. The second line contains n space-separated integers describing the respective values of a[0],a[1],...,a[n-1].

Constraints

  • 2 <= n <= 600
  • 1 <= a[i] <= 2 x 10^6, for all i in [0, n-1]

Output Format

  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.