Python Program to sort the elements of an array in ascending order


February 17, 2022, Learn eTutorial
1311

How to sort an array in python without using any method?

In this python program, we need to sort the elements in an array in ascending order. The array is a set of elements of the same data type. To sort the array, use nested for loops. The outer loop is used to take an element, and the inner loop is to compare that with every other element. When an element with a lower value is found, it will be swapped with the comparing element using an if condition in python. Repeat the loops to sort every element in the array to get all the elements sorted.

Let us take an example array with elements [5, 3, 1, 2 4], then we take the first element 5 and compare that with the other elements, so we compare it with 3, and it is smaller than 5, so it gets swapped with 3. Finally, we get the array sorted. In this Basic python program on arrays, we are using a predefined array with some elements. Then we use a temp variable initialize with zero. After displaying the original array we use nested for loop and swap the elements using temp variable, finally print the sorted array using a for loop.

ALGORITHM

STEP 1: Initialize the array with some predefined values.

STEP 2: Define a variable temp with the value zero.

STEP 3: We print the original array using a for loop using a range method.

STEP 4: Start the outer for loop from zero to the length of the array for comparing one element.

STEP 5: Open the inner for loop from i+1 to the array's length to compare the element with all other elements.

STEP 6: Use an if condition to check if the selected element is greater than the comparing element,

STEP 7: Swap the selected element with the lesser element and do that till the end of for loop to get the array fully sorted.

STEP 8: Print the sorted array using for loop and print in the python programming language


To sort an array using python we need to know about the below topics, please refer to these topics to get a better understanding

Python Source Code

                                          arr = [5, 2, 3, 4, 1];     
temp = 0;    
         
print("Elements in 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 ascending order: ");    
for i in range(0, len(arr)):     
    print(arr[i]),   
                                      

OUTPUT

Elements in original array
5, 2, 3, 4, 1

Array sorted in ascending order
1, 2, 3, 4, 5