java数据结构希尔排序交换法实现代码
时间: 2023-12-10 22:35:07 浏览: 43
以下是Java实现希尔排序交换法的代码:
```java
public static void shellSort(int[] arr) {
int len = arr.length;
int temp, gap = len / 2;
while (gap > 0) {
for (int i = gap; i < len i++) {
for (int j = i - gap; j >= 0 && arr[j] > arr[j + gap]; j -= gap) {
temp = arr[j];
arr[j] = arr[j + gap];
arr[j + gap] = temp;
}
}
gap /= 2;
}
System.out.println(Arrays.toString(arr));
}
```
相关问题
c语言数据结构希尔排序代码
以下是C语言实现希尔排序的代码示例:
```c
#include <stdio.h>
#include <stdbool.h>
void shellSort(int arr[], int n) {
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;
}
}
}
void display(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Input Array: ");
display(arr, n);
shellSort(arr, n);
printf("Output Array: ");
display(arr, n);
return 0;
}
```
数据结构 希尔排序代码
```python
def shellSort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
arr = [12, 34, 54, 2, 3]
shellSort(arr)
print("排序后的数组:", arr) # 输出:[2, 3, 12, 34, 54]
```
相关推荐
![](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)