使用指针交换数据
void swap(int* num1, int* num2) { int test; test = *num1; *num1 = *num2; *num2 = test; }
非指针交换并排序(低到高)
void lowtoheight(int height[],int len) { int test = 0; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (height[i] > height[j]) { //交换身高 test = height[i]; height[i] = height[j]; height[j] = test; } } } }
指针交换(高到低)
void heighttolow(int low[], int len) { int test = 0; for (int i = 0; i < len; i++) { for (int j = i + 1; j < len; j++) { if (low[i] < low[j]) { //交换身高 /*test = low[i]; low[i] = low[j]; low[j] = test;*/ swap(&low[i], &low[j]); } } } }
int main(void) { int height[] = { 163, 161, 158, 165, 171, 170, 163, 159, 162 }; int len = sizeof(height) / sizeof(height[0]);//长度 lowtoheight(height, len); for (int i = 0; i < len; i++) { cout << height[i] << endl; } cout << "---------------------------------------" << endl; heighttolow(height, len); for (int i = 0; i < len; i++) { cout << height[i] << endl; } cin.get(); return 0; }
交换后:
158 159 161 162 163 163 165 170 171
---------------------------------------
171 170 165 163 163 162 161 159 158