### 算法和算法復雜度

#找出一個列表中最小值的索引
def index_of_min(shuffle_list):
index_min = 0
for i in range(len(shuffle_list)):
if shuffle_list[i] < shuffle_list[index_min]:
index_min = i
return index_min

index_of_min([3,6,1,4,5])#算法必須經過n-1次比較，復雜度為O(n)

#numpy中函數實現找出列表中最小值的索引
import numpy as np
np.argmin([3,6,1,4,5])

def order_search(target,lst):
for i in lst:
if i == target:
return True
return False

order_search(3,[4,5,6,7])#算法最少判斷一次，最多要判斷n次，算法復雜度為O(n)

def binary_search(target,ordered_lst):
left = 0
right = len(ordered_lst) - 1
while left <= right:
center = (left + right) // 2
if target == ordered_lst[center]:
return True
else:
if target < ordered_lst[center]:
right = center - 1
else:
left = center + 1
return False

binary_search(300,[3,5,6,7,9,10,12,18,30])

__eq__,__lt__,__gt__
#實現能一個進行比較操作的類
class compare_operation():
'''該類實現比較操作'''
def __init__(self,data):
self.data = data
def __eq__(self,other):
return self.data == other.data
def __lt__(self,other):
return self.data < other.data
def __gt__(self,other):
return self.data > other.data
a = compare_operation(4)
b = compare_operation(5)


def seleclt_sorted(shuffled_lst):
index_location = 0#算法開始的位置
while index_location < len(shuffled_lst) - 1:#從第一個位置開始循環
min_index = index_location
index = index_location + 1
while index < len(shuffled_lst):#從算法開始位置，找出列表中的最小值
if shuffled_lst[min_index] > shuffled_lst[index]:
min_index = index
index += 1
shuffled_lst[index_location],shuffled_lst[min_index] = shuffled_lst[min_index],shuffled_lst[index_location]#最小值和算法開始位置值交換
index_location += 1#后面循環起始位置加1
return shuffled_lst


def bubble_sorted(shuffled_lst):
for i in range(len(shuffled_lst)):
for j in range(i+1,len(shuffled_lst)):
if shuffled_lst[i] > shuffled_lst[j]:
shuffled_lst[i],shuffled_lst[j] = shuffled_lst[j],shuffled_lst[i]
return shuffled_lst

def insection_sorted(shuffled_lst):
i = 1#第一個要插入的值
while i < len(shuffled_lst):
insert_value = shuffled_lst[i]
j = i -1
while j >= 0:
if insert_value < shuffled_lst[j]:
shuffled_lst[j+1] = shuffled_lst[j]#如果當前值比要插入的值要大，就后移一位
j -= 1
else:
break #前i-1個值都是已經排序的好的，所以循環到大於的情況就可以停止了
shuffled_lst[j+1] = insert_value#插入值
i += 1#插入的值的索引自增
return shuffled_lst


#快排實現
def sort_partion(shuffled_list,left,right):
pivot_index = left
pivot = shuffled_list[left]
for i in range(left+1,right+1):
if shuffled_list[i] < pivot:#遍歷列表開始判斷該數是否小於基數
pivot_index += 1
if pivot_index != i:
shuffled_list[pivot_index],shuffled_list[i] = shuffled_list[i],shuffled_list[pivot_index]
shuffled_list[left],shuffled_list[pivot_index] = shuffled_list[pivot_index],shuffled_list[left]
return pivot_index
def quick_sort(shuffled_list,left,right):
if left < right:
pivot_index = sort_partion(shuffled_list,left,right)
quick_sort(shuffled_list,left,pivot_index-1)
quick_sort(shuffled_list,pivot_index+1,right)
return shuffled_list