插入排序java代码实现
时间: 2023-10-10 18:16:08 浏览: 54
下面是插入排序的Java代码实现:
```java
public class InsertionSort {
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;
}
}
}
```
这里我们使用了一个 for 循环来遍历整个数组,然后使用一个 while 循环来将当前元素插入到已排序的子数组中。在 while 循环中,我们将 arr[j] 向右移动,以便为当前元素腾出空间。最后,我们将当前元素插入到正确的位置。
相关问题
插入排序java代码
当然可以!以下是插入排序的Java代码示例:
```java
public class InsertionSort {
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;
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 1};
insertionSort(arr);
System.out.println("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
这段代码实现了插入排序算法。在主函数中,我们创建了一个整数数组 `arr`,其中包含待排序的元素。然后调用 `insertionSort` 方法来对数组进行排序,并打印排序后的结果。
希望以上代码能对你有所帮助!如果有任何问题,请随时提问。
插入排序java代码运行
好的,以下是Java实现的插入排序代码:
```java
public class InsertionSort {
public static void sort(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;
}
}
public static void main(String[] args) {
int[] arr = { 12, 11, 13, 5, 6 };
sort(arr);
for (int i = 0; i < arr.length; ++i) {
System.out.print(arr[i] + " ");
}
}
}
```
运行结果为:
```
5 6 11 12 13
```
相关推荐
![](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)