數組排序程式

來源:互聯網
上載者:User

標籤:i+1   位置   執行   大小   倒數   最小   inpu   變數   pen   

1、十個評委給學生打分,規則是去掉最高分和最低分,然後求平均值。

  分析:首先求出最高分和最低分,然後再求和,最後再求平均值。

     先把十個分數看成是一個列表裡的元素,求最高分時,先假設第一個最大,然後去跟相鄰的比較,如果大就保留,如果小就保留另一個。

     關鍵是不能引入外值,只能在十個分數裡選一個先作為最大的,然後去比較。求最小是同樣的道理。

  用while迴圈寫的程式

  

a = []
i = 0
while i<10:
score = int(input("請輸入分數:"))
a.append(score)
i+=1
i = 0
score_min = a[0]
score_max = a[0]
score_sum = 0
score_avg = 0
while i<10:
if a[i] > score_max:
score_max = a[i]
if a[i] < score_min:
score_min = a[i]
score_sum = score_sum + a[i]
i +=1
score_avg = (score_sum-score_max-score_min)/8
print("最大的分數是:",score_max)
print("最小的分數是:",score_min)
print("分數的平均值是:",score_avg)

  用for迴圈寫的程式

score_list = []for i in range(10):    score = float(input("請輸入分數:"))    score_list.append(score)score_max = score_list[0]score_min = score_list[0]score_sum = 0for i in range(10):    if score_list[i] > score_max:        score_max = score_list[i]    if score_list[i] < score_min:        score_min = score_list[i]    score_sum = score_sum + score_list[i]score_avg = (score_sum - score_max - score_min)/8print("去掉最大值:%.2f\t去掉最小值:%.2f\n最終的平均得分是:%.2f"%(score_max,score_min,score_avg))

2、冒泡排序

  分析:加入給一個列表啊 a=[9,8,7,6,5],如果要想從小到大排序,需要第一個位置的數依次跟其他位置的數比較,比相鄰的大,就互換位置,最終到最後的位置。五個元素,迴圈四次才能確定最大的到最後位置,然後剩四個元素不確定順序,然後再迴圈比較三次,確定倒數第二個位置,這樣最終需要確定四個位置就需要四趟,每一趟就比上一趟少迴圈一次。

  關鍵:四趟是一個外大迴圈,外迴圈的次數就是列表的長度減去1

     每一趟的迴圈都比上一趟少一次,是一個根外迴圈參數先關的內迴圈,作用是確定大小位置

     內迴圈的比較,有可能需要交換彼此的位置,所以,要有一個交換的演算法,就是引入一個變數c,當a[i]>a[i+1]時,執行

     c = a[i]

     a[i] = a[i+1]

     a[i+1] = c,最後實現前後位置的值互換

  下面是用while迴圈寫的程式

  

a = [9,8,7,6,5]j = 0while j<4:    i = 0    while i<(4-j):        if a[i] > a[i+1]:            t = a[i]            a[i] = a[i+1]            a[i+1] = t        i += 1    j += 1print(a)

  下面是用for迴圈寫的程式

  

a = [9,8,7,6,5]for j in range((len(a)-1)):    for i in range((len(a)-1)-j):        if a[i] > a[i+1]:            c = a[i]            a[i] = a[i+1]            a[i+1] = c    print(a)

 

  

數組排序程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.