我想更改当前的插入排序算法以对文件进行排序,但我不知道从哪里开始。到目前为止,这是我的代码:
def insertionSort(arr):
for i in range(1,len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j]:
arr[j+1]=arr[j]
j -=1
arr[j+1] = key
答案 0 :(得分:0)
您要根据什么依据对文件进行排序? [例如。关于修改的数据或名称]
只需使用import os
文件是按字母顺序而不是数字顺序排序的。。
以不同的方式排序
import os
def extractDataOrIndex(fileName):
# do something to return date or index
return date
def insertionSort(arr):
for i in range(1,len(arr)):
dataOrIndexOfCurrentFile = extractDataOrIndex(arr[i]) #have some logic here to extract date or Index
j = i-1
dataOrIndexOfPrevFile = extractDataOrIndex(arr[j]) #have some logic here to extract date or Index
while j >=0 and dataOrIndexOfCurrentFile < dataOrIndexOfPrevFile:
arr[j+1]=arr[j]
j -= 1
if j>=0 :
dataOrIndexOfPrevFile = extractDataOrIndex(arr[j])
arr[j+1] = arr[i]
arddDir = os.listdir()
print(arddDir) # you can see its already sorted by name
insertionSort(arddDir)
for i in range(0,len(arr)):
print(arr[i]) # to see sorted file on the basis of some parameter other than