python语言实现排序算法

版权声明:未经本人许可,不得用于商业用途及传统媒体。转载请注明出处! https://blog.csdn.net/qikaihuting/article/details/78289960

1. Bubble Sort ——冒泡排序

思想:持续比较相邻元素,大的挪到后面,因此大的会逐步往后挪,第一趟结果是最大的数在最后一个元素,故称之为冒泡。

话不多说直接上代码

def bubble_sort(arr):
    #从小到大的排序
    print(arr)
    for i in range(len(arr)-1):   
        for j in range(1,len(arr)-i):
            if arr[j] < arr[j-1]:
                arr[j-1],arr[j] = arr[j],arr[j-1]
                '''
                temp = arr[j]
                arr[j] = arr[j-1]
                arr[j-1] = temp
                '''
    return arr

if __name__ == '__main__':
    print(bubble_sort([6,2,9,4,2,7,1,5]))

2. select_sort ——选择排序

思想:不断地选择剩余元素中的最小者。

1.每一躺找到数组中最小元素并将其与数组中最前面的位置交换。

2. 逐渐往后比较,直至整个数组排序。

def select_sort(arr):
    for i in range(len(arr)-1):
        min_index = i
        for j in range(i+1,len(arr)):
            #找到较小的数对应的索引
            if arr[j] < arr[min_index]:
                min_index = j
        arr[min_index] , arr[i] = arr[i] , arr[min_index]
        
    return arr

if __name__ == '__main__':
    print(select_sort([6,2,9,4,2,7,1,5]))

3. insert_sort——选择排序

思想:将待排序列看作为无序序列,通过建立有序序列,逐渐将无序序列中的元素插入到有序序列合适的位置,直至无序序列为空。

1. 从第一个元素开始,该元素是有序的,余下的数组是无序的

2. 依次遍历无序中的元素(外循环),同时对前面有序的数组元素从后往前遍历(内循环), 若所遍历的有序序列中的元素大于当前元素,则将有序的索引index移至下一位置,再次与当前元素比较,直到找到有序序列中元素小于或等于当前元素的位置

3. 插入当前元素到该位置

4. 重复2~3

def insert_sort(arr):
   
    for i,item in enumerate(arr):
        index = i
        #index用来寻找已排序列的合适位置,找到之后与item交换
        while(index > 0 and arr[index-1] > item):
            arr[index] = arr[index -1]
            index -=1
        arr[index] = item
        
    return arr

if __name__ == '__main__':
    print(insert_sort([6,2,9,4,2,7,1,5]))

4. 实际排序问题

问题描述:txt文件中有两列字段,第一列是str型的人脸图片绝对路径;第二列是对应人脸的质量评分,根据评分,完成对人脸图片的排序,对应关系不变。

思想:借鉴hash思想,将路径或者下标当做键,进行排序。

# -*- coding: utf-8 -*-

import os
from collections import defaultdict
import numpy as np
import time 
#divide the data into three subsets according to score of each image

def sort_dict(file_name ,dest_dir):
    bagan = time.time()
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)
        
    with open(file_name,'r') as f:
        #len(f.readlines())
        list_tuple = [(item.split()[0],float(item.split()[1])) for item in f.readlines()]
     
    #build the dict for (img_path, score) pairs
    d = defaultdict(list)
    for key, value in list_tuple:
        d[key] = value
        
    # sort the dict according to score from high to low  
    s_sorted = sorted(zip(d.values(),d.keys()),reverse=True)
    
    # write the result into txt files
    with open(dest_dir+'1V4w_score_sorted.txt','w') as f:
        for item in s_sorted:
            f.write(item[1]+' '+str(item[0])+'\n')
            
    print('finish had costed is %d'%(time.time()-bagan))

def sort_index(file_list, dest_dir) :
    bagan = time.time()
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)
        
    src_path_ = []
    src_score_ = []
    
    with open(file_list,'r') as f:
        # split the path and score and save as list
        for line in f.readlines():
            img_path, score_img = line.split(' ')
            src_path_.append(img_path)
            src_score_.append(-float(score_img))
    #get the index array of up_to_down sorted score 
    idx =  np.argsort(src_score_)

    print(len(idx))
    # find the highest img_name based on index 
    with open("{0}/sorted_1v4w_scores.txt".format(dest_dir), "w") as f:
        # write the current prior item into txt after each cycle iteration
        for i in range(0,len(src_score_)):
            index = idx[i]
            prior_name = src_path_[index]
            prior_score = src_score_[index]
            f.write("{0} {1}\n".format(prior_name, str(abs(prior_score))))
			
    print('finish had costed is %d'%(time.time()-bagan))
                       
            
if __name__=='__main__':
    #sort_dict(r'1v4w_scores.txt',r'./')
    sort_index(r'./Desktop/1v4w_scores.txt',r'.')




猜你喜欢

转载自blog.csdn.net/qikaihuting/article/details/78289960