DAY 1
0
Software Development

# 拉蒙碎碎念

``````data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]
``````

``````data = [23, 23, 29, 34, 55, 66, 67, 78, 78, 79, 88, 89, 92, 96, 96, 100]
``````

## 1. 準備桶子

``````max_score = 100
bucket = []
for i in range(max_score+1):
bucket.append(0)
``````

## 2. 丟垃圾 分類成績

``````for score in data:
bucket[score] = bucket[score] + 1
``````

## 3. 回收垃圾 讀取成績

``````index = 0
for i in range(len(bucket)):
if bucket[i] != 0:
for j in range(bucket[i]):
data[index] = i
index += 1
``````

## 全部的程式碼

``````data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]

def bucketsort(data):
max_score = 100
bucket = []

for i in range(max_score+1):
bucket.append(0)
for score in data:
bucket[score] = bucket[score] + 1

index = 0
for i in range(len(bucket)):
if bucket[i] != 0:
for j in range(bucket[i]):
data[index] = i
index += 1

bucketsort(data)
print(data)
``````

## 花式自虐 進階練習

``````data = [['Abby', 58], ['Julia', 44], ['Jane', 31], ['Stephen', 76], ['Ryn', 82], ['Justin', 99], ['Caroline', 65], ['James', 87], ['Damon', 25], ['Elena', 76]]
``````

``````data = [['Abby', 58], ['Julia', 44], ['Jane', 31], ['Stephen', 76], ['Ryn', 82], ['Justin', 99], ['Caroline', 65], ['James', 87], ['Damon', 25], ['Elena', 76]]

def bucketsort_hash(data):
max_score = 100
bucket = []
bucket_num = lambda x: int(x/33)

for i in range(bucket_num(max_score)+1):
bucket.append([])

for x in data:
index = bucket_num(x[1])
bucket[index].append(x)

for i, flag in enumerate(bucket):
if flag != [] :
bucket[i] = sorted(bucket[i], key=lambda x: x[1])

index = 0
for i in bucket:
if i != []:
for j in i:
data[index] = j
index += 1

bucketsort_hash(data)
print(data)
``````

30天學演算法和資料結構31

### 1 則留言

0
Desolve
iT邦新手 5 級 ‧ 2020-06-24 16:15:19