Advertisement
JAS_Software

Bubble and Insertion Sort

Apr 26th, 2021
65
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from random import randint
  2. from random import sample
  3.  
  4. def generateRandomList(numberOfElements):
  5.     elements = []
  6.     for i in range(0,numberOfElements):
  7.         value = randint(1,100)
  8.         elements.append(value)
  9.     return elements
  10.  
  11. def generateRandomAlphabet():
  12.     letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  13.     elements = sample(letters,26)
  14.     return elements
  15.  
  16. def bubbleSort(elements):
  17.     print('Bubble Sort')
  18.     swapped = True
  19.     n = len(elements) - 1
  20.     while swapped:
  21.         swapped = False
  22.         for i in range(n):
  23.             if elements[i] > elements[i+1]:
  24.                 #elements[i], elements[i+1] = elements[i+1],elements[i]
  25.                 elements.insert(i+1,elements.pop(i))
  26.                 swapped = True
  27.         n -= 1
  28.     return elements
  29.  
  30. def insertionSort(elements):
  31.     print('Insertion Sort')
  32.     #Loop through items
  33.     for item in range(1,len(elements)):
  34.         #get the item to be moved into a sorted postion
  35.         marker = item - 1
  36.         key = elements[item]
  37.        
  38.         #Loop through sorted items until the correct sorted position is found
  39.         #Or the start of the sorted list is reached
  40.         while elements[marker] < key and marker >= 0:
  41.             elements[marker + 1] = elements[marker]
  42.             elements[marker] = key
  43.             marker -= 1
  44.         print(elements)
  45.     return elements
  46.  
  47. #elements = generateRandomList(10)
  48. elements = generateRandomAlphabet()
  49. #elementsSorted = bubbleSort(elements[:])
  50. print('Original List: {}'.format(elements))
  51. elementsSorted = insertionSort(elements[:])
  52. print('Sorted List  : {}'.format(elementsSorted))
  53.  
  54.  
  55.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement