帮我写一个 java 的希尔排序
时间: 2023-11-22 09:57:36 浏览: 31
当然!帮你写希尔排序的 Java 代码如下:
```
public class ShellSort {
public static void sort(int[] arr) {
int n = arr.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
}
```
使用方式也非常简单,只需要在主函数中调用 `ShellSort.sort(arr)` 即可对数组 `arr` 进行希尔排序。希望这份代码能够对你有所帮助!哈哈,顺便给你一个笑话吧:为什么 Java 程序员只喜欢喝红茶?因为 Java 不支持无限 T。
相关问题
写一个希尔排序java实现
希尔排序是一种改进的插入排序算法,它通过将数组分成多个子序列来提高插入排序的效率。以下是一个希尔排序的Java实现示例:
```java
public class ShellSort {
public static void shellSort(int[] arr) {
int n = arr.length;
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
public static void main(String[] args) {
int[] arr = {9, 5, 1, 4, 3, 2, 8, 7, 6};
shellSort(arr);
System.out.println("排序结果:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
用java写一个希尔排序
好的,这是用 Java 实现希尔排序的代码:
```
public void shellSort(int[] arr) {
int n = arr.length;
// Start with a big gap, then reduce the gap
for (int gap = n/2; gap > 0; gap /= 2) {
// Do a gapped insertion sort for this gap size.
// The first gap elements arr[0..gap-1] are already
// in gapped order keep adding one more element
// until the entire array is gap sorted
for (int i = gap; i < n; i += 1) {
// add arr[i] to the elements that have been gap
// sorted save arr[i] in temp and make a hole at
// position i
int temp = arr[i];
// shift earlier gap-sorted elements up until
// the correct location for arr[i] is found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
// put temp (the original arr[i]) in its correct
// location
arr[j] = temp;
}
}
}
```
希尔排序是一种插入排序,它的思想是使数组中任意间隔为 h 的元素都是有序的。这样的数组被称为 h 有序数组。对于任意以 1 结尾的 h,将是有序的。
上面的代码实现了希尔排序的基本思想:
- 首先,使用一个大的 gap 值来分组。
- 然后,逐渐减小 gap 值,直到 gap=1 为止。
- 对于每个 gap 值,使用插入排序来排序元素。
希尔排序的时间复杂度为 O(n^2),但由于它对元素的排序是分组进行的,因此实际上它的性能要优于普通的插入排序。