#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int a[]={10,29,33,44,51,11,23,45,6,72,43,3}; int n; n=sizeof (a)/sizeof (a[0]);//計算數組元素個數 //數組排序前打印 printf("befor:"); for (int i=0;i<n;i++) { printf("%d ",a[i]); } printf("\n"); //排序 int temp; for (int i=0;i<n;i++) { for (int j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } //數組排序後打印 printf("After:"); for (int i=0;i<n;i++) { printf("%d ",a[i]); } printf("\n"); return 0; } 運行結果:
函數封裝: //若是數組做爲函數參數,數組形參退化爲指針 //void printf_array(int a[10],int n) //void printf_array(int *a,int n) void printf_array(int a[],int n) { for (int i=0;i<n;i++) { printf("%d ",a[i]); } printf("\n"); } void sort_array(int a[],int n) { int temp; for (int i=0;i<n;i++) { for (int j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } } int main() { int a[]={10,29,33,44,51,11,23,45,6,72,43,3}; int n; n=sizeof (a)/sizeof (a[0]); printf("befor:\n"); printf_array(a,n); sort_array(a,n); printf("after:\n"); printf_array(a,n); return 0; }
運行結果:
數組