用Java写代码:对数组A[]={1,3,5,46,11,22,37,45,44,78,67,98}进行排序
时间: 2024-06-13 18:08:24 浏览: 8
以下是使用Java对数组进行排序的代码:
```java
public class SortArray {
public static void main(String[] args) {
int[] A = {1, 3, 5, 46, 11, 22, 37, 45, 44, 78, 67, 98};
int temp;
for (int i = 0; i < A.length - 1; i++) {
for (int j = i + 1; j < A.length; j++) {
if (A[i] > A[j]) {
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
for (int i = 0; i < A.length; i++) {
System.out.print(A[i] + " ");
}
}
}
```
相关问题
用Java写代码:对数组A[]={1,3,5,46,11,22,37,45,44,78,67,98}进行插入排序
以下是Java实现对数组进行插入排序的代码:
```java
public class InsertionSort {
public static void main(String[] args) {
int[] A = {1, 3, 5, 46, 11, 22, 37, 45, 44, 78, 67, 98};
insertionSort(A);
for (int i : A) {
System.out.print(i + " ");
}
}
public static void insertionSort(int[] A) {
for (int i = 1; i < A.length; i++) {
int key = A[i];
int j = i - 1;
while (j >= 0 && A[j] > key) {
A[j + 1] = A[j];
j--;
}
A[j + 1] = key;
}
}
}
```
使用Java用冒泡排序对数组a={23,4,32,67,42,42,41,32,15}进行从小到大排序。
好的,下面是Java代码实现:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] a = {23, 4, 32, 67, 42, 42, 41, 32, 15};
// 冒泡排序
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
// 输出排序结果
System.out.print("从小到大排序结果: ");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
```
这段代码会对给定数组进行冒泡排序,将数组元素从小到大排序,并输出排序结果。排序过程中,每一次循环都将相邻的两个元素进行比较,如果前一个元素比后一个元素大,则交换两个元素的位置。重复这个过程,直到所有元素都按照从小到大的顺序排列。
相关推荐
![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)