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:
Array is sorted in numSwaps swaps.
wherenumSwaps
is the number of swaps that took place.First Element: firstElement
wherefirstElement
is the first element in the sorted array.Last Element: lastElement
wherelastElement
is the last element in the sorted array.
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:
Array is sorted in numSwaps swaps.
wherenumSwaps
is the number of swaps that took place.First Element: firstElement
wherefirstElement
is the first element in the sorted array.Last Element: lastElement
wherelastElement
is the last element in the sorted array.
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