写一个从小到大排序的C++代码
时间: 2023-05-18 21:05:57 浏览: 51
以下是一个简单的从小到大排序的C代码:
```c
#include <stdio.h>
void sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main() {
int arr[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int i;
sort(arr, n);
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这个代码使用了简单的选择排序算法,它遍历数组中的每个元素,找到比当前元素小的元素,并将它们交换位置。最终,数组中的元素将按从小到大的顺序排列。
相关问题
用C++代码写一个冒泡排序从小到大最简单
以下是用C++语言实现冒泡排序的代码:
```c++
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 5, 2, 9, 1, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
```
输出结果:
```
Sorted array: 1 2 5 5 6 9
```
在上面的代码中,我们使用了两个嵌套的循环。外层循环用来控制排序轮数,内层循环用来比较相邻元素的大小并交换它们。最后输出排序后的数组。
用c++写一个从小到大的冒泡排序
以下是用 C 语言编写的从小到大的冒泡排序代码:
```c
#include <stdio.h>
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = { 5, 2, 8, 3, 1, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
printf("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
该代码使用了双重循环,外层循环控制排序的轮数,内层循环控制每一轮中相邻元素的比较和交换。在每一轮中,如果相邻元素的顺序不正确,就交换它们的位置,直到所有元素都按照从小到大的顺序排列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)