Skip to content

Instantly share code, notes, and snippets.

@SammyHerring
Created February 1, 2016 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SammyHerring/688aadf44a4299709f73 to your computer and use it in GitHub Desktop.
Save SammyHerring/688aadf44a4299709f73 to your computer and use it in GitHub Desktop.
Python-based sorting algorithm for bubble sorting and insertion sorting.
#Import Random Module for Array Generation
import random
#BubbleSort Algorithm for given array in parameters
def bubbleSort(listsort):
for num in range(len(listsort)-1,0,-1):
for i in range(num):
if listsort[i]>listsort[i+1]:
x = listsort[i]
listsort[i] = listsort[i+1]
listsort[i+1] = x
#InsertionSort Algorithm for given array in parameters
def insertionSort(listsort2):
for index in range(1,len(listsort2)):
currentvalue = listsort2[index]
position = index
while position>0 and listsort2[position-1]>currentvalue:
listsort2[position]=listsort2[position-1]
position = position-1
listsort2[position]=currentvalue
#Main procedural script for user interaction
def main():
#User Input the required number of random strings
n = input("Enter required bumber of random strings in array: ")
while n < 1: #Validation to ensure there are more than one random strings
print("Error! Sort requires more than one string.")
print("Try again.")
n = input("Enter required bumber of random strings in array: ")
print("")
x = int(n)
a = random.sample(range(1,9999),x) # Random string generation through Random module
print("Unordered List: ") # Print Unordered List
print(a)
print("")
listsort = a
listsort2 = a
bubbleSort(listsort)
insertionSort(listsort2)
print("Bubble Ordered List: ")
print(listsort) # Print Ordered List
print("")
print("Insertion Ordered List: ")
print(listsort2)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment