Jump to content

[PYTHON] Sort an array


Wikkie
 Share

Recommended Posts

In this post ,we are going to see how to sort an array list manually without using sort() method in python

Function 1:

def get_list_of_values(): 
  array=[] #Created an empty list to store the values
  limit = int(input("Enter the number of list elements you want :")) # getting the limit for list generation
  for i in range(0,limit): # Looping until i reaches the limit value
    value = int(input(f'Enter the value_{i+1} : ')) # Getting the value from the user
    array.append(value) # Adding the values to our array list 
  print(f'[Before SORT]\n{array}') 
  sort_the_list_of_values(array) # Calling the sort_the_list_of_values and passing the array list

 

Function 2:

def sort_the_list_of_values(array): 
  for i in range(0,len(array)): #looping until i reaches the total length of the list
    for j in range(0,len(array)-1): #looping until i reaches the total length of the list
      if(array[j]>array[j+1]): # checking whether the current list value is greater than the next list value
        temp = array[j]  #assigning the current selected list value in a temp variable
        array[j] = array[j+1] #Swapping the list values  
        array[j+1] = temp #Swapping the list values 
  print(f'[After SORT] {array}') 

 

Calling the initial function:

get_list_of_values()

 

Output

Enter the number of list elements you want :10
Enter the value_1 : 9
Enter the value_2 : 8
Enter the value_3 : 7
Enter the value_4 : 6
Enter the value_5 : 5
Enter the value_6 : 4
Enter the value_7 : 3
Enter the value_8 : 2
Enter the value_9 : 1
Enter the value_10 : 0
[Before SORT]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[After SORT]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

 

Additional source :

 I hope it is useful ❤

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.