Python 实现的"冒泡排序"

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
    ''''' 
    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();  

标签: swap

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:GPS 经纬度转换为 经过旋转后的平面坐标

下一篇:用PyQt实现透明桌面时钟小部件!