函數指針的應用比較排序與冒泡排序指針完成

// 利用函數指針來實現比較排序 冒泡排序
// 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;
	}
	
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章