选择排序(C/C++)
使用指针交换数据
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!