python实现冒泡,快排,选择和插入排序
1.冒泡排序
def my_sort(array):
flag=1
for i in range(len(array)):
if(flag==1):
flag=0
for j in range(len(array)-i-1):
if(array[j]>array[j+1]):
temp=array[j]
array[j]=array[j+1]
array[j+1]=temp
flag=1
else:
break
return array
2.选择排序
def quick_sort(low,high,array):
solder=array[low]
while(low<high):
if(array[high]<solder):
array[low]=array[high]
low+=1
while(low<high):
if(array[low]>solder):
array[high]=array[low]
high-=1
break
else:
low+=1
else:
high-=1
array[high]=solder
return array,highdef recursion(array,low,high):
if low<high:
array,middle=quick_sort(low,high,array)
recursion(array,low,middle-1)
recursion(array,middle+1,high)
print(array)
3.选择排序
#选择排序
def chocice_sort(array):
#由于array不支持index,将其转为list来做
array=list(array)
for i in range(len(array)):
try:
data=None
data=array[i:]
print(type(data))
index=array.index(min(data))
temp=array[i]
array[i]=array[index]
array[index]=temp
#print(array)
except:
pass
continue
print(array)
4.插入排序
#直接插入排序
def dir_sort(array):
for i in range(1,len(array)):
temp=array[i]
for j in range(i-1,-1,-1):
print(array)
if (array[j]>temp)&(j==0):
array[1]=array[0]
array[0]=temp
break
if (array[j]>temp)&(j!=0):
array[j+1]=array[j]
continue
if(array[j]<temp):
array[j+1]=temp
break
#print(array)
#调用
data=np.array([0]*10)
for i in range(10):
data[i]=random.randint(1,100)
#print(data)
#print(len(data.shape))
#data=recursion(data,0,9)
#chocice_sort(data)
dir_sort(data)
1
|
<br style
=
"">
|
- 点赞
- 收藏
- 关注作者
评论(0)