如何用c++的if语句实现排序
时间: 2024-05-16 13:15:11 浏览: 18
使用if语句进行排序通常需要结合其他的循环控制语句,如while或for循环。
以下是使用if和for语句实现选择排序的示例代码:
```c++
#include<iostream>
using namespace std;
int main()
{
int arr[10] = {5, 2, 9, 3, 8, 4, 0, 1, 7, 6};
int temp;
for(int i=0; i<10; i++)
{
for(int j=i+1; j<10; j++)
{
if(arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i=0; i<10; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
该代码使用选择排序对数组进行排序。在内部循环中,if语句用来比较当前元素和后面元素的大小,如果当前元素大于后面的元素,就交换它们的位置。
需要注意的是,if语句只是用来比较元素大小的条件语句,真正的排序操作是在if语句内部的代码块中完成的。
相关问题
用c++嵌套的if语句对输入的三个数排序
好的,我可以回答这个问题。以下是用 C 嵌套的 if 语句对输入的三个数排序的代码:
```c
#include <stdio.h>
int main() {
int a, b, c;
printf("请输入三个整数:\n");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (a > c) {
if (b > c) {
printf("%d %d %d\n", a, b, c);
} else {
printf("%d %d %d\n", a, c, b);
}
} else {
printf("%d %d %d\n", c, a, b);
}
} else {
if (b > c) {
if (a > c) {
printf("%d %d %d\n", b, a, c);
} else {
printf("%d %d %d\n", b, c, a);
}
} else {
printf("%d %d %d\n", c, b, a);
}
}
return 0;
}
```
希望能对你有所帮助。
c++语言嵌套的if语句对输入的三个数排序
可以回答这个问题。以下是一个示例代码:
#include <stdio.h>
int main() {
int a, b, c;
printf("请输入三个整数:\n");
scanf("%d%d%d", &a, &b, &c);
if (a > b) {
if (a > c) {
if (b > c) {
printf("%d %d %d\n", a, b, c);
} else {
printf("%d %d %d\n", a, c, b);
}
} else {
printf("%d %d %d\n", c, a, b);
}
} else {
if (b > c) {
if (a > c) {
printf("%d %d %d\n", b, a, c);
} else {
printf("%d %d %d\n", b, c, a);
}
} else {
printf("%d %d %d\n", c, b, a);
}
}
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)