定义一维数组int array【5】={-1,2,9,6,8,10};实现此数组元素从大到小的排序
时间: 2024-05-12 15:16:39 浏览: 11
可以使用冒泡排序,代码如下:
```
int array[5] = {-1, 2, 9, 6, 8, 10};
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5-i-1; j++) {
if (array[j] < array[j+1]) {
int temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
// 打印排序后的数组
for (int i = 0; i < 5; i++) {
cout << array[i] << " ";
}
```
注意原数组有6个元素,应该改为 int array[6]。
相关问题
用c语言定义一维数组int array【5】={-1,2,9,6,8,10};实现此数组元素从大到小的排序
好的,我可以回答这个问题。请使用冒泡排序算法,将数组元素从大到小排序,以下是代码示例:
```
#include <stdio.h>
void bubbleSort(int arr[], int n);
int main() {
int array[5] = {-1, 2, 9, 6, 8};
int i;
bubbleSort(array, 5);
printf("Sorted array in descending order: ");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
return 0;
}
void bubbleSort(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;
}
}
}
}
```
输出结果为:
```
Sorted array in descending order: 9 8 6 2 -1
```
java 3、定义一维数组int[] array = {5,3,6,4,9,2,8,1,7},对它进行升序排序,得到一个有序的数组并输出到控制台;
好的,以下是 Java 代码实现:
```java
public class Main {
public static void main(String[] args) {
int[] array = {5, 3, 6, 4, 9, 2, 8, 1, 7};
int len = array.length;
// 冒泡排序
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
// 打印结果
for (int i = 0; i < len; i++) {
System.out.print(array[i] + " ");
}
}
}
```
输出结果为:
```
1 2 3 4 5 6 7 8 9
```
这里使用了冒泡排序算法对数组进行升序排序。
相关推荐
![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)