Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
community creator

What is large to small sort in Python?

Aarthi Reddy

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

  1. Sort the given list using the sort() function.

  2. Find the maximum and minimum values in the list and sort them according to the given condition.

Example

The given list is [2,3,4,6][2,3,4,6]:

  • The maximum number is 66.
  • The second maximum number is 44.
  • The minimum number is 22.
  • The second minimum number is 33.

So, the required list will be [6,2,4,3][6,2,4,3].

Implementation

nums=[2, 3, 4, 6]
nums.sort()
l=[]
i = 0
j = len(nums) - 1
while i < j:
l.append(nums[j])
l.append(nums[i])
i=i+1
j=j-1
if i == j:
l.append(nums[i])
print(l)

Explanation

  1. The given list is sorted in ascending order so we can easily identify the maximum and minimum numbers.

  2. An empty list is taken to store the final sorted values.

  3. Two variables i and j are used as index valuesused to access elements of the list. i is assigned to 0 and is used to access minimum numbers. j is assigned to the maximum index and is used to access maximum numbers in the sorted list.

  4. The while loop is used to append values in the empty list until the condition is satisfied. The i value is incremented and the j value is decremented to find the second maximum and minimum numbers.

  5. The list is printed and the given condition is satisfied.

svg viewer

RELATED TAGS

python
community creator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring