演算法_冒泡程式,演算法冒泡程式

來源:互聯網
上載者:User

演算法_冒泡程式,演算法冒泡程式

這裡的第一個演算法,沒什麼可以說的,一定是從最經典的冒泡演算法開始,會列出python版和c版

冒泡演算法很簡單,就是像冒泡一樣,把小的,也可以理解成輕的,從下面浮出來

比如有個list = [3,2,5,4,1],先用3和2比,2輕,2浮上去,3沉下去,3再和5比,3比較輕,位置不變,5和4比,4浮上來,5和1比,1浮上來

第一次比完,得到[2,3,4,1,5],再進行第二次,第三次,直到把沒有可以浮的了,就結束,通常這個演算法的版本是嵌套迴圈,就是for for,好像掉進這個圈出不來了,其實不用全部比一遍,如果list初始就是[2,1,3,4,5],其實只要第一次就可以得到結果了,後面不是無用功麼

好了,閑話不多,上代碼,邊嗑瓜子,邊喝茶,邊看代碼,人生一大幸事啊

虛擬碼

序列 = [3,2,5,4,1]迴圈序列  標記初始化,直到標記沒有變化,就結束迴圈  如果第一個>第二個    第二個和第一個換位置    標記值變化,記錄有變化了  回到頭,重新迴圈  

python版

#!/usr/bin/python# coding: UTF-8def bubble_sort(num_list):  num_len = len(num_list)  while True:    n = 0    '''range這裡-1是因為下面的+1,如果不-1,下面+1後會報out of range錯誤,而且從演算法來說最多尋找len(list) - 1次,因此這個是沒問題的'''    for i in range(num_len-1):      if num_list[i] > num_list[i+1]:        num_list[i],num_list[i+1] = num_list[i+1],num_list[i] #交換位置        n += 1    if n == 0:      break  return num_listif __name__ == '__main__':  num_list = [3,2,5,4,1]  print num_list  num_list = bubble_sort(num_list)  print num_list

c版

 

#include <stdio.h>int main(){  int num[] = {3,2,5,4,1};  int i,num_len1;  num_len1 = sizeof(num)/4; //這個sizeof的結果是20,我也不知道咋算的,不是說一個數字佔1bit$  bubble_sort(num,num_len1);  for(i=0; i<num_len1; i++)  {    printf("%d \n", num[i]);  }  return 0;}int bubble_sort(int num_list[],int num_len){  int i;  while(1)  {    int n = 0;    for(i=0;i<(num_len-1);i++)    {      if(num_list[i] > num_list[i+1])      {        int temp = num_list[i];        num_list[i] = num_list[i+1];        num_list[i+1] = temp;        n++;      }    }    if(n == 0)    {      break;    }  }  return 0;}

不得不說,c真的很難適應,不過總會適應的,一起加油把

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.