用Java对数列{3,9,5,1,11,7}冒泡排序
时间: 2023-03-16 22:44:43 浏览: 70
Java语言进行冒泡排序:
int[] arr = {3,9,5,1,11,7};
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
相关问题
用Java对数列{3,9,5,1,11,7}冒泡排序,并说出需要循环几次才能完成排序
要完成数列{3,9,5,1,11,7}的冒泡排序需要循环5次。示例代码如下:int[] array = {3,9,5,1,11,7};for (int i = 0; i < array.length - 1; i++)
{
for (int j = 0; j < array.length - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
java冒泡排序发排序
Java中的冒泡排序是一种简单的排序算法,它的基本思想是重复地遍历要排序的数列,比较相邻的元素,如果它们的顺序错误就把它们交换过来。遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
以下是冒泡排序的基本步骤:
1. 比较相邻的元素。如果第一个比第二个大,就交换它们的位置。
2. 对每一对相邻元素做同样的比较,从开始第一对到结尾的最后一对。这一步做完后,最大的元素会“浮”到数列的末尾。
3. 针对剩下的未排序元素重复上述步骤,但每次遍历时少一个元素(因为最大的元素已经在最后)。
4. 重复这个过程,直到整个数列排序完成。
这是一个简单的Java实现:
```java
public class BubbleSort {
void bubbleSort(int arr[]) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
// 测试方法
public static void main(String args[]) {
BubbleSort bs = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
bs.bubbleSort(arr);
System.out.println("Sorted array: ");
for (int i = 0; i < arr.length; ++i) {
System.out.print(arr[i] + " ");
}
}
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)