In this simple python program, we need to sort an array in python in descending order. It's a sorting python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this simple python program on sorting, we need to sort the elements in descending order, which means we need to sort the elements from Largest to the Smallest. It is almost the same as sorting in ascending order.
In this simple python program, we use nested two for loops in python. The outer
for loop is for taking each element from the array, and the inner
for loop is to compare that element in the array using an if condition. If the '
if condition' is satisfied, which means if any element is larger than the selected element, we have to swap the elements' position using a temp variable.
After all the iterations of the inner and outer for loop, we have the array sorted in descending order. Finally, we print the array using another for loop. In this python program, we are using a pre-defined array with some elements. Then we print the array using a for loop to display the original array. Then we use a nested for loop and an if condition to compare each element in the array with every other element in the same array and swap the element if any element we found less than the comparing element, after swapping the element with a
STEP 1: Initialize an array with some elements in it.
STEP 2: Initialize a variable temp for swapping.
STEP 3: Display the array using
for loop in python language.
STEP 4: Start the outer for loop from zero to the length of the array.
STEP 5: Start the inner loop and compare each element of the array with the outer loop element.
STEP 6: If the selected element is lesser than the comparing element. Then we swap the position of the elements using the temp variable in each iteration.
STEP 7: Print the resultant sorted array using print in python programming.
arr = [5, 2, 3, 4, 1]; temp = 0; print("original array: "); # printing the original array for i in range(0, len(arr)): print(arr[i]), for i in range(0, len(arr)): for j in range(i+1, len(arr)): # comparing the elements using nested for loop if(arr[i] < arr[j]): temp = arr[i]; arr[i] = arr[j]; # swapping the elements arr[j] = temp; print(); print("Array sorted in descending order: "); for i in range(0, len(arr)): print(arr[i]),
original array [5, 2, 3, 4, 1] Array sorted in descending order 5 4 3 2 1