程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Three sorts (select, bubble, insert) Python version

編輯:Python
class select:
def select_sort(self):
# Selection sort
# Compare the first with the rest , Find the smallest , Then swap the smallest with the first , At this time, the first one is the smallest
# Then compare the second with the rest , Find the smallest , Then swap the smallest with the second , At this time, the second one is the second small one
# And so on , Sort , This is a selection sort , The time complexity is O(n^2)
arr = [7, 2, 9, 4, 4, 8]
n = len(arr)
if not arr or n < 2:
return -1
for i in range(n-1):
min = i
for j in range(i+1, n):
min = j if arr[j] < arr[min] else min
self.swap(arr, i, min)
return arr
def swap(self, arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
class bubble:
def bubble_sort(self):
# Bubble sort
# Compare the first two , Two small ones are in front , The big one is behind , Then compare the second with the third , The small one is in the front, the big one is in the back , Finally get the biggest at the end .
# The second cycle is still the same , But don't look at the last one at this time , Because the last one is the biggest one
# So circular , Get the biggest one each time and put it at the end , The time complexity is O(n^2)
arr = [7, 2, 9, 4, 4, 8]
n = len(arr)
if not arr or n < 2:
return -1
for i in range(n):
for j in range(n-i-1):
if arr[j]>arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
class insert:
def insert_sort(self):
# Insertion sort
# First, let 0~0 Orderly (0~0 Not considering , A number must be ordered ), And then there was 0~1,0~2....
# Every interval , At last, I thought I would look forward , If it's smaller than the one in front , Just like the previous exchange , Until the front of the exchange
# The time complexity is O(n^2)
arr = [7, 2, 9, 4, 4, 8]
n = len(arr)
if not arr or n < 2:
return -1
for i in range(1, n):
j = i - 1
while j >= 0:
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
j -= 1
return arr

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved