Two-point Search
def bin_search (Data_set, Val): Low = 0 High = Len (data_set)-1 when Low <= High: mid = (low + high)// 2 if Data_set[mid]==val: return mid elif Data_set[mid] < val: Low = mid + 1 else: high = mid- 1data = [1,4,2,5,63,4]res = Bin_search (data,63) print (res)
Bubble sort
Idea: First the list of every two adjacent number, if the front is larger than the back, then exchange these two numbers.
Import Randomdef Bubble_sort (List1): For I in range (len (list1)-1): For J in Range (Len (list1)-i-1): if List1 [j]>list1[j+1]: list1[j],list1[j+1] = List1[j+1],list1[j]data = List (range) random.shuffle (data) #[2, 3, 13 , 0, +, 6, 1, 4, 8, ten, 7, one, 9, 5]print (data) res = bubble_sort (data) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 , 14]print (data)
After optimization
Import Randomdef Bubble_sort (List1): For I in range (len (list1)-1): exchange = False for j in Range (Len (list1 )-i-1): if (List1[j]) > (list1[j+1]): list1[j],list1[j+1] = list1[j+1],list1[j] Exchange = True If Not exchange: Breakdata = list (range) random.shuffle (data) print (data) # [5, 1, 14, 13, 6, 15, 7, 12, 2, 16, 11, 9, 8, 3, 4, 0, 19]bubble_sort (data) print (data) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1 8, 19]
Select sort
Idea: A trip through the smallest number of records, put in the first position, and then go through the record remaining list of the smallest value, placed
Import randomdef Select_sort (LI): for I in range (Len (LI)-1): min_loc = i for j in Range (I+1,len (LI)): If Li[j]<li[min_loc]: min_loc = J Li[i],li[min_loc] = Li[min_loc],li[i]data = List (range) Random.shuffle ( Data) print (data) select_sort (data)
Insert Sort
Import randomdef Insert_sort (LI): for I in range (1,len (LI)): temp = li[i] j = i-1 while j>=0 and Li[j ]>temp: li[j+1] = li[j] j = j-1 li[j+1] = TempData = List (range) random.shuffle (data) print (data) Insert_sort (data) print (data)
Quick Line
Idea: 1, take an element p (the first element), so that the element P is returned to the position
2, the list is divided into two parts p, the left is smaller than P, the right side is greater than P
3, Recursive complete sorting
Summary: Follow me, right hand one slow motion, right hand left hand slow action replay
def quick_sort (data,left,right): If left < right: mid = partition (Data,left,right) quick_sort (data, left,mid-1) Quick_sort (data,mid+1,right) def partition (data,left,right): tmp = Data[left] while left < right: the while left<right and data[right]>=tmp: # Left hand-- = 1 data[left] = Data[right] while Left<right and Data[left]<=tmp: # Left Ieft + + 1 data[right] = Data[left] data[left] = tmp return Leftimport Randomdata = list (range) random.shuffle (data) print (data) # [19, 4, 0, 7, 14, 8, 2, 12, 11, 17, 13, 3, 6, 1, 5, Data,0,len, 9]quick_sort (data)-1) print (data) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Common algorithms for Python development