Posts

Showing posts with the label SORTING

MERGE SORT

Image
Algorithm Divide the list in two half if length not = 1 or 2 sort left half  sort right half  merge the two  merging: compare the first element of each half then choose(and remove) the smaller , then check the next index of the sub list from which ele1 was chosen and repeat it until both sublists become empty IMAGE: CODE:  l1=[] n=int(input("Enter the number of elements in list: ")) for e in range(n):     ele=int(input("Enter value for element: "))     l1.append(ele) print("Original list :",l1) def merge(la,lb):     l1=list(la)     l2=list(lb)     l4=[]     i=(len(l1)+len(l2))     while len(l4)<i:         if len(l1)==0 or len(l2)==0:             l4=l4+l1+l2             break         if l1[0]>=l2[0]:             l4.append(l2.pop(0))         else:...

Bubble sort in Python

Image
 It is one of the simplest sorting techniques where it traverses the whole list by comparing adjacent elements and swapping to move the biggest element to the end one at a time. eg. list. [4,2,9,1,7,6] after step 1 [2,4,1,7,6,9] after step 2 [2,1,4,6,7,9] after step 3 [1,2,4,6,7,9] after step 4 [1,2,4,6,7,9] after step 5 [1,2,4,6,7,9] CODE: l1=list() n=int(input("Enter the number of elements in list: ")) for e in range(n):     ele=int(input("Enter value for element: "))     l1.append(ele) print("Original list :",l1) for i in range (1,n): #in the outer loop it will traverse through each index from 1 till the last     for j in range(0,n-i):         if l1[j]>l1[j+1]:             l1[j+1],l1[j]=l1[j],l1[j+1] # if current element is bigger than the following element # then their positions will be swapped             print(f"changing place of {l1[j+1]} and {l1[j]}: ")   ...

Insertion Sort in python

Image
 In Insertion Sort , we sort the element in a list by taking 1 element at at a time and placing it in a position of sorted order. For eg , let a list be [45,23,56,8,34] In step 1 the first two elements will be compared and arranged accordingly . Then in step 2 the third element will be compared with the first two elements and inserted to create an order (ascending or descending) among the three elements and this process will be continued until all the elements have been arranged. CODE: l1=list() n=int(input("Enter the number of elements in list: ")) for e in range(n):     ele=int(input("Enter value for element: "))     l1.append(ele) print("Original list :",l1) for i in range (1,n): #in the outer loop it will traverse through each index from 1 till the last     for j in range(0,i): # in 2nd loop each element will be compared with every element before it         if l1[i]<l1[j]:             l1[i],l1[j]...