C++通過指針實現一位數組的冒泡排序算法。
冒泡排序
冒泡排序(Bubble Sort),是一種計算機科學領域的較簡單的排序算法。
代碼:
1 /* 2 Name:冒泡排序算法 3 Copyright:Null 4 Author:小X 5 Date: 06-10-14 10:34 6 Description:C++通過指針實現一維數組的冒泡排序 7 */ 8 9 #include <iostream> 10 11 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 12 #include <stdio.h> 13 #include <stdlib.h> 14 15 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 16 void sort(int* a,int len) 17 { 18 int i,j,t; 19 for(i=0;i<len-1;i++) 20 { 21 for(j=0;j<len-1-i;j++) 22 { 23 if(a[j]>a[j+1]) 24 { 25 t=a[j]; 26 a[j]=a[j+1]; 27 a[j+1]=t; 28 } 29 } 30 } 31 } 32 33 int main(int argc, char** argv) 34 { 35 int a[6]={1563,454,56,32,48456,455}; 36 sort(a,6); 37 int i; 38 for(i=0;i<6;i++) 39 { 40 printf("第%d個數是%d\n",i+1,a[i]); 41 } 42 return 0; 43 }
運行結果:
代碼講解:
一維數組的數組名代表的是數組的第一個元素的地址,我們在傳遞參數的時候需要兩個參數,一個是首地址,另一個是數組元素的個數,
至少需要這兩個參數才能確定一維數組。
End!
歡迎大家一起交流 ,分享程序員勵志故事。 幸福的程序員 QQ群: