30 Day code challenge-python

Day 20— Sorting

Task

Given an array, a, of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm. Once sorted, print the following 3 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.
Sample input and output

Input Format

The first line contains an integer, n, the number of elements in array a.
The second line contains n space-separated integers that describe a[0], a[1],…, a[n-1].

Output Format

Print the following three lines of output:

  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.
Solution

Explanation

Line 1–3: Gets input from the user, total defines the no of swaps occurrs while sorting.

Line 4–10: Sort the values in ascending order. If the value is smaller than the previous value then both the values are swapped.

Line 11–13: Prints the total number of swaps, first and last element.

Bonus Tip: We can sort values using Bubble sort, Merge sort and Quicksort. In that Quicksort is the most efficient sorting algorithm.

See you on day 21

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store