函數指標作為函數參數,實現冒泡排序的升序排序和降序排序

來源:互聯網
上載者:User

標籤:函數指標

#include<stdio.h>#define N 10//定義數組元素個數int Ascending(int a,int b);//升序排列的函式宣告int Descending(int a,int b);//降序排列的函式宣告void swap(int*,int*);//交換資料的函式宣告void BubbleSort(int a[],int n,int (*compare)(int,int));//聲明排序函數,通過函數指標作為函數調用void Display(int a[],int n);//輸出數組元素的函式宣告void main(){int a[N]={12,34,21,46,89,54,26,8,6,17};int flag;while(1){printf("輸入1:從小到大排序。\n輸入2:從大到小排序\n輸入3:退出!\n");scanf("%d",&flag);switch(flag){case 1:printf("排序前的資料為:");            Display(a,N);BubbleSort(a,N,Ascending);//從小到大排序,將函數作為參數傳遞printf("從小到大排列後的資料為:");Display(a,N);break;case 2:            printf("排序前的資料為:");            Display(a,N);BubbleSort(a,N,Descending);//從大到小排序,將函數作為參數傳遞printf("從大到小排列後的資料為:");Display(a,N);break;case 3:return;break;default:printf("輸入資料不合法,請重新輸入。\n");break;}}}//冒泡排序,將函數作為參數傳遞,判斷是從小到大還是從大到小排序void BubbleSort(int a[],int n,int(*compare)(int,int)){int i,j;for(i=0;i<n;i++){for(j=0;j<n-1;j++)if((*compare)(a[j],a[j+1]))swap(&a[j],&a[j+1]);}}//交換數組的元素void swap(int *a,int *b){int t;t=*a;*a=*b;*b=t;}//判斷相鄰資料的大小,如果前者大,升序排列需要交換int Ascending(int a,int b){if(a>b)return 1;elsereturn 0;}//判斷相鄰資料的大小,如果前者大,降序排列需要交換int Descending(int a,int b){if(a<b)return 1;elsereturn 0;}void Display(int a[],int n)//輸出資料元素{    int i;for(i=0;i<n;i++)printf("%5d",a[i]);printf("\n");}

程式運行結果



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

函數指標作為函數參數,實現冒泡排序的升序排序和降序排序

聯繫我們

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