003Scratch:氣泡排序法01
教學影片
<待上傳>
Scratch程式設計與程式設計流程圖
Python程式設計
程式碼1-1:氣泡排序法
a=int(input("請輸入數字1:"))#指定變數a為輸入的數字 input獲得的資料型態為string(字串) 用int()轉為整數資料型態。
b=int(input("請輸入數字2:"))#指定變數b為輸入的數字 input獲得的資料型態為string(字串) 用int()轉為整數資料型態。
c=int(input("請輸入數字3:"))#指定變數c為輸入的數字 input獲得的資料型態為string(字串) 用int()轉為整數資料型態。
if a>b:#如果a>b時 兩者互換
tmp=b#將變數tmp設為變數b值
b=a#將變數b設為變數a的值
a=tmp#將變數a設為變數tmp的值
if b>c:
tmp=c
c=b
b=tmp
if a>b:
tmp=b
b=a
a=tmp
print("三數字依大小排序後由大至小分別為 [%d] [%d] [%d] " %(c,b,a))#輸出由大至小的結果 即CBA的順序
程式碼1-2:氣泡排序法
python可以直接交換數值:A↔B要交換,就指定A,B=B,A即可。
a=int(input("請輸入數字1:"))
b=int(input("請輸入數字2:"))
c=int(input("請輸入數字3:"))
if a>b:
a,b=b,a
if b>c:
b,c=c,b
if a>b:
a,b=b,a
print("由小至大分別為 [%d] [%d] [%d] " %(a,b,c))
程式碼2:用串列List的方法.sort()排序由小到大
data=[]#宣告data為空串列
for i in range(3):#共重複3次 i=0,1,2
data.append(int(input("請輸入數字:")))#新增串列資料方法.append()來新增資料
data.sort()#自動排序
print(data)#輸出
程式碼3:用串列List的方法.sort(),反向排序由大到小
data=[]
for i in range(3):
data.append(int(input("請輸入數字:")))
data.sort(reverse=True)#加入參數reverse=True可以將「小→大」排序,改成「大→小」排序。
print(data)