函数指针的应用比较排序与冒泡排序指针完成

来源:互联网 发布:3dsmax 安装mac 编辑:程序博客网 时间:2024/05/18 13:45

// 利用函数指针来实现比较排序 冒泡排序
// test.cpp : Defines the entry point for the console application.//<pre name="code" class="cpp">// test.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <IOSTREAM>using namespace std;void max_min(int* p, int m, int* max, int* min);void BubbleSort(int* p, int m);/*冒泡排序*/void SelectSort(int* p, int m);/*选择排序*/int main(int argc, char* argv[]){int a[10] = {23,12,-56,48,16,-12,20,0,-9,66};int n = 10;void (*fp)(int*, int, int*, int*);int max,min,*pmax = &max, *pmin = &min;fp = max_min;(*fp)(a,n,pmax,pmin);cout<<endl;cout<<max<<"  "<<min<<endl;int ch = 2;void (*fs)(int*, int);/*函数指针*/switch(ch){case 1:{ fs= BubbleSort; fs(a, n);   }break;case 2:{fs = SelectSort;fs(a, n);}break;default:break;}for(int i = 0; i < n; ++i){cout<<a[i]<<" ";}printf("Hello World!\n");return 0;}void max_min(int* p, int m, int* pmax, int* pmin){*pmax = *pmin = *p;for(int i = 0; i < m; ++i){if (*pmax < *(p+i)){*pmax = *(p+i);}if (*pmin > *(p+i)){*pmin = *(p+i);}}}/*冒泡排序  最坏情况下O(N*N)*/void BubbleSort(int* p, int m){int i,j;int flag;for (i = 0; i < m; ++i){flag = 1;for(j = i+1; j < m; ++j){if (*(p+i) > *(p+j)){flag = 0;int temp = *(p+i);*(p+i) = *(p+j);*(p+j) = temp;}}if (flag){break;}}}/*选择排序 O(N*N)*/void SelectSort(int* p, int m){int i,j;int k;for (i = 0; i < m; ++i){k = i;for(j = i+1; j < m; ++j){if (*(p+k) > *(p+j)){k = j;}}int temp = *(p+i) ;*(p+i) = *(p+k);*(p+k) = temp;}}


1 0
原创粉丝点击