1

## 系列篇章統整: 小馬的資料結構演算法筆記 (主要是用c++程式實作)

### 1 則留言

0
ovo815428
iT邦新手 5 級 ‧ 2020-06-05 13:10:46

``````
def Insertion_Sort(data):
size = 0
i = 0

print('\nPlease enter number to sort (enter 0 when end): ') # 要求輸入資料直到輸入為零
while True:
i += 1
data.append(int(input('#%d number: ' % i)))
if data[size] == 0:
break
size += 1

for i in range(60):
print('-', end = '')
print()

sorting(data, size)

for i in range(60):
print('-', end = '')

print('\nSorted data : ', end = '')
for i in range(size):
print('%d ' % data[i], end = '')

def sorting(data, size):
print('First data is %d\n' % data[0])

***# 當資料小於第一筆，則插於前方，否則與後面資料比對找出插入位置***
for base in range(1, size):
temp = data[base]
compare = base
print('Inserting data is ', data[base])
while compare>0 and data[compare-1] > temp:
data[compare] = data[compare-1]
data[compare-1] = temp
compare -= 1

print('After #%d insertion: ' % base, end = '')
for i in range(base+1):
print(data[i], ' ', end = '')
print('\n')

def main():
data = []
Insertion_Sort(data)

main()
``````
``````# -*- coding: utf-8 -*-
"""
108-2 Data Structure

WK14-practice_14_2
"""

def quick_sort(data):
size = 0
i = 0

print('\nPlease enter number to sort (enter 0 when end): ') # 要求輸入資料直到輸入為零
while True:
i += 1
data.append(int(input('#%d number: ' % i)))
if data[size] == 0:
break
size += 1

for i in range(60):
print('-', end = '')
print()

sorting(data, 0, size-1, size)

for i in range(60):
print('-', end = '')

print('\nFinal sorted data: ', end = '')
for i in range(size):
print(data[i], ' ', end = '')

def sorting(data, left, right, size):
#left與right分別代表欲排序資料兩端
if left < right:
lbase = left + 1
while data[lbase] < data[left]:
if lbase+1 > size:
break
lbase += 1
rbase = right
while data[rbase] > data[left]:
rbase -= 1
while lbase < rbase: # 若lbase小於rbase，則兩資料對調
data[lbase], data[rbase] = data[rbase], data[lbase]
lbase += 1
while data[lbase] < data[left]:
lbase += 1
rbase -= 1
while data[rbase] > data[left]:
rbase -= 1
data[left], data[rbase] = data[rbase], data[left] # 此時lbase大於rbase，則rbase的資料與第一筆對調

print('Sorting: ', end = '')
for i in range(size):
print('%4d' % data[i], end = '')
print()

sorting(data, left, rbase-1, size)
sorting(data, rbase+1, right, size)

def main():
data = []
quick_sort(data)

main()

``````

1. 這門課是你買線上課程自學的，還是在學校內修課的?(高中或大學?)
2. 在選這門課之前，你有學習過任何程式語言的基礎嗎?
3. 若您是大學生的話，願意告訴我你的科系嗎?
4. 你可以補充說明任何有助於我了解你的學習背景的描述。