用Java写2331的插入排序
时间: 2023-08-10 11:32:56 浏览: 44
好的,下面是Java代码实现2331的插入排序:
```java
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
```
其中,arr为待排序数组,n为数组长度。在排序过程中,从第二个元素开始遍历,将当前元素与前面已排序的元素依次比较,找到合适的位置插入。
相关问题
用Java写124插入排序
好的,以下是用Java写的124插入排序的代码:
```java
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {1, 2, 4};
insertionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
```
这段代码实现了对数组 {1, 2, 4} 的插入排序。其中,insertionSort() 方法接收一个整型数组作为参数,使用插入排序算法对数组进行排序。具体来说,算法通过维护一个已排序子序列和一个未排序子序列,每次将未排序子序列中的元素插入到已排序子序列的合适位置,最终得到一个有序的数组。
用Java写1234插入排序
好的,以下是用Java写的1234插入排序的代码:
```java
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
insertionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
```
这段代码实现了对数组 {1, 2, 3, 4} 的插入排序。其中,insertionSort() 方法接收一个整型数组作为参数,使用插入排序算法对数组进行排序。具体来说,算法通过维护一个已排序子序列和一个未排序子序列,每次将未排序子序列中的元素插入到已排序子序列的合适位置,最终得到一个有序的数组。
相关推荐
![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)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)