What is large to small sort in Python?
Large to small sort is when a list is sorted in ascending order. This means that the first number in the list is the maximum, the second number is the minimum, the third number is the 2nd maximum, the fourth number is the 2nd minimum, etc.
What is a sorted list?
A sorted list contains numbers sorted in ascending order. If a list contains strings, then the list is sorted in alphabetical order. The sorted() function is used to perform sorting operations.
Algorithm
-
Sort the given list using the
sort()function. -
Find the maximum and minimum values in the list and sort them according to the given condition.
Example
The given list is :
- The maximum number is .
- The second maximum number is .
- The minimum number is .
- The second minimum number is .
So, the required list will be .
Implementation
nums=[2, 3, 4, 6]nums.sort()l=[]i = 0j = len(nums) - 1while i < j:l.append(nums[j])l.append(nums[i])i=i+1j=j-1if i == j:l.append(nums[i])print(l)
Explanation
-
The given list is sorted in ascending order so we can easily identify the maximum and minimum numbers.
-
An empty list is taken to store the final sorted values.
-
Two variables
iandjare used as .index values used to access elements of the list iis assigned to0and is used to access minimum numbers.jis assigned to the maximum index and is used to access maximum numbers in the sorted list. -
The while loop is used to append values in the empty list until the condition is satisfied. The
ivalue is incremented and thejvalue is decremented to find the second maximum and minimum numbers. -
The list is printed and the given condition is satisfied.