Python By Example

Sort the elements of an array

by Jiffin Joachim Gomez on 24th February 2017

This is a Python program to sort the elements of a one dimensional array in ascending order. The sorting algorithm used in this program is known as Bubble sort.

At first the program prompts the user to input the array elements. The input string is split using the split() function and typecasted to integer.

The array_sort() function checks the first and second elements of the array. If the first element is greater than the second element then they are swapped. Next the second element is checked with the third element and if the second element is greater then it is swapped. This continues up to the last element of the array. The array is sorted when no more swaps are needed on the array. The swap() function is used just to swap the position of two elements of an array.

#importing the standard array module
from array import *

#swapping the array elements
def swap(new_array, a, b):
    temp = new_array[a]
    new_array[a] = new_array[b]
    new_array[b] = temp

#array sorting function
def array_sort(new_array):
        swapped = True
        while swapped:
            swapped = False
            for i in range(1, len(new_array) - 1):
                if new_array[i-1] > new_array[i]:
                    swap(new_array, i-1, i)
                    swapped = True

#Read user input
input_str = input("Input all array elements seperated by space character: ")

#initializing the array
my_array = array('i',[ int(i) for i in input_str.split()] )

#Find array length

#passing the array elements to the sort function 

#print array elements
print("Array sorted in ascending order")
for i in my_array:
    print(i, end=' ')

Program Output

Input all array elements seperated by space character: 5 4 6 8 12 10 15 33
Array sorted in ascending order
4 5 6 8 10 12 15 33 

Post a comment


Nothing the first to share wisdom.