''''' Bubble Sort @author: aihua.sun ''' import string import random number = []; count = 0; def bubbleSort(): #initializeNumberArray(); generateRandomNumberArray(10, 1, 300); showArray(); sort(); showArray(); def showArray(): print(number); #Manual input number def initializeNumberArray(): print("Please input array of integer, and input Q will get sort of result!"); while True: inputCommand = input("input a number:"); if inputCommand != "Q": #must indicator count is global variable global count; count += 1; number.append(inputCommand); else: break; #automatic generate random number array def generateRandomNumberArray(lenght, minNumber, maxNumber): #must indicator count is global variable global count; for index in range(lenght): number.append(random.randrange(minNumber, maxNumber)); count = index; def sort(): for reverseIndex in range(count - 2, 0, -1): for index in range(reverseIndex): behindIndex = index + 1; if needSwap(number[index], number[behindIndex]): swapByIndex(index, behindIndex); def needSwap(previousNumber, behindNumber): return int(previousNumber) > int(behindNumber); def swapByIndex(previousNumber, behindNumber): number[previousNumber], number[behindNumber] = number[behindNumber], number[previousNumber]; if __name__ == "__main__": bubbleSort();
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8251.html