要求使用指针实现数组成员由小到大的顺序排列第二版

有一个整形数组, a[3] = {7,2,5}, 要求使用指针实现数组成员由小到大的顺序排列,即
结果为:a[3] = {2,5,7};

第二版:

#include <stdio.h>
#include <iostream>
#include <Windows.h>

using namespace std;

void order(int* a, int* b) {
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

int main(void) {
	int a[3] = { 7,5,2 };

	//先保证前面两个数有序
	if (*a > * (a + 1)) {
		//int tmp = *a;
		//a=*(a+1);
		//(a-1) = tmp;
		order(a, a + 1);
	}

	if (*(a + 2) < *(a + 1)) {
		order(a + 1, a + 2);

		if (*(a + 1) < *a) {
			order(a, a + 1);
		}
	}

	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++) {
		cout << a[i] << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ZengYong12138/article/details/106751717