java利用冒泡排序实现数组 { 1, 8, 7, 5, 4 }从小到大排序
时间: 2024-03-05 10:53:19 浏览: 26
好的,下面是利用冒泡排序实现数组从小到大排序的Java代码:
```java
public static void main(String[] args) {
int[] arr = { 1, 8, 7, 5, 4 };
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
```
运行结果为:[1, 4, 5, 7, 8]
这段代码中,我们使用了两层循环来实现冒泡排序,外层循环控制排序的轮数,内层循环控制每轮比较的次数。在每轮比较中,如果前一个数比后一个数大,则交换它们的位置。最终得到的结果就是从小到大排序的数组。
相关问题
用java中的冒泡排序实现数组按照从小到大排序输出
好的,下面是Java中冒泡排序算法的实现,用于将数组按照从小到大排序输出:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1, 6};
bubbleSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] arr) {
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
输出结果为:
```
1 2 3 5 6 8
```
以上就是用Java中的冒泡排序算法实现数组按照从小到大排序输出的方法。
Java编写程序,利用排序算法实现数组 scores 里面的数据的从小到大排序输出
好的,以下是Java代码实现:
```java
public class SortScores {
public static void main(String[] args) {
int[] scores = {90, 87, 93, 78, 84, 92, 88};
// 使用冒泡排序算法从小到大排序
for (int i = 0; i < scores.length - 1; i++) {
for (int j = 0; j < scores.length - 1 - i; j++) {
if (scores[j] > scores[j + 1]) {
int temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
// 输出排序后的数组元素
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + " ");
}
}
}
```
输出结果为:
```
78 84 87 88 90 92 93
```
相关推荐
![](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)