直接排序算法python实现

    技术2022-05-18  12

    一直对算法不是很上心,今天跟同事聊天,了解到算法很吃香呀!

    刚开始学习python,就一个一个的算法来吧!希望有时间能坚持下去!

    大家别拍砖!我只是留个笔记在这里。

    直接排序法直接选择排序法的算法是这样的,首先选出前n个元素中的最小(大)者,如果这个最小(大)者不是第1个元素,则与第1个元素交换,然后以同样的方法对付后 n-1个元素(分治),直到处理的元素只剩一个,即得到有序序列。它和冒泡排序法很类似,不同的是冒泡排序法进行了更多次的交换,而有些交换是不必要的,这使得冒泡排序法是不稳定的,而直接选择排序法是稳定的排序法。

     

    def directSort(olist): if olist == None or list != type(olist): return olist ; if len(olist)<2:return olist; lens = len(olist)-1 while lens>0: maxIndex = None for i in range(0,lens): if maxIndex == None: if olist[i] > olist[lens]: maxIndex = i else: if olist[i] > olist[maxIndex]: maxIndex = i if maxIndex != None: switch(olist,lens,maxIndex) lens = lens -1 print olist def switch(olist,firstIndex,lastIndex): print "交换----%s_%s" %(olist[firstIndex],olist[lastIndex]) tmp = olist[firstIndex] olist[firstIndex] = olist[lastIndex] olist[lastIndex] = tmp tmpList =[8,6,54,34,293,-54,4459,1,23,-2,34] #tmpList =[3] print tmpList directSort(tmpList) print tmpList

     


    最新回复(0)