Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

bubble sort with code optimization

arr = [12,1,6,23,234,456,2,35,687,34]
# arry consists of 9 elements

n = len(arr)
#conts the element of the arry 

for j in range(n-1):            #this is for list to get shorted properly && you dont need to go full as it may take more steps to exicute
    for i in range(n-j-1):      #if left with n the there will be array error because it will try to add 1 to n in below leading to array being bigger                                             
        if arr[i]>arr[i+1]:                                         
            arr[i],arr[i+1]=arr[i+1],arr[i]
        else:
            pass
#       arry starts from last and eventually decrease the number lower and lower which leads to lesser steps
#       #above took 125 steps to eully exicute
#################################################################        
#       #this takes 217 steps to run and end code
# for i in range(n):
#     if arr[i]>arr[i+1]:
#         arr[i],arr[i+1]=arr[i+1],arr[i]        
#     else:
#         pass
#################################################################    
print("the sorted array is : "arr)
Comment

PREVIOUS NEXT
Code Example
Python :: python codes 
Python :: pytorch mse mae 
Python :: range function 
Python :: numpy transpose 
Python :: A Python Class Constructor 
Python :: Python message popup 
Python :: python key from values 
Python :: numpy savetxt list of strings 
Python :: dataframe pandas empty 
Python :: python remove spaces from string 
Python :: python how to add to a list 
Python :: python swap function 
Python :: python type hinting pandas dataframe 
Python :: python list of dictionaries 
Python :: python how to align text writen to a file 
Python :: how to hide ticks marks in plot 
Python :: hugging face change directory model 
Python :: delete variable python 
Python :: monty hall problem in python 
Python :: make venv 
Python :: python slice 
Python :: creating new virtual environment in python 
Python :: pandas dataframe for loop begin end index 
Python :: random letters generator python 
Python :: python venv usage 
Python :: python dict copy() 
Python :: gradient descent 
Python :: check if an object has an attribute in Python 
Python :: how to print in double quotes in python 
Python :: create new list with for loop python 
ADD CONTENT
Topic
Content
Source link
Name
6+2 =