冒泡排序
比较相邻两个字符,如果左边大于右边,则交换位置,遍历一遍字符后,则最大的肯定在最右边;继续循环处理剩下的字符(最右边的不用再比较了,已经最大了)
代码实现:
def BubbleSort(sourceStr): l = list(sourceStr) cnt = len(l)-1 while cnt >= 0: i = 0 j = 0 while i < cnt: j = i + 1 if l[i] > l[j]: tmp = l[j] l[j] = l[i] l[i] = tmp i+=1 cnt-=1 return ''.join(l) if __name__ == '__main__': myStr = '125694520' print(' Before Sort: %s \n After Sort: %s' %(myStr,BubbleSort(myStr)) )
执行结果:
C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exe E:/wangjz/PyWorkSpace/LearnPython/test_order.py Before Sort: 125694520 After Sort: 012245569 Process finished with exit code 0
选择排序
每次从字符串中选择最小的值,放到新的列表中,选完一个,原字符串就去掉最小的那个;直到选完,新的列表也组成了
代码实现:
def SelectSort(sourceStr): oldList = list(sourceStr) newList = [] maxStr = '' while oldList!=[]: maxStr = min(oldList) newList.append(maxStr) oldList.remove(maxStr) return ''.join(newList) if __name__ == '__main__': myStr = '125694520' # print(' Before Sort: %s \n After Sort: %s' %(myStr,BubbleSort(myStr)) ) print(' Before Sort: %s \n After Sort: %s' %(myStr,SelectSort(myStr)) )
执行结果:
C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exe E:/wangjz/PyWorkSpace/LearnPython/test_order.py Before Sort: 125694520 After Sort: 012245569 Process finished with exit code 0