- 论坛徽章:
- 0
|
本帖最后由 jack1007 于 2012-10-24 13:44 编辑
之前纠结半天,还是分开写好理解多了,先写直接插入排序函数,再用插入排序函数进行希尔分组排序。- #include <stdio.h>
- void swap(int *a, int *b);
- void print_arr(int *arr, int arr_len);
- void shellsort(int *arr, int arr_len);
- void insertion_sort(int *int_arr, int div_len, int arr_len);
- int
- main()
- {
- int arr[] = {99, 56, 48, 93, 25, 32, 49, 88, 12, 74, 22, 62};
- int arr_len = sizeof(arr) / sizeof(arr[0]);
- print_arr(arr, arr_len);
- shellsort(arr, arr_len);
- print_arr(arr, arr_len);
- return 0;
- }
- void
- insertion_sort(int *arr, int div_len, int arr_len)
- {
- int i, j;
- for (i = div_len; i < arr_len; i+=div_len) {
- for (j = i; arr[j] < arr[j - div_len] && j > 0; j-=div_len) {
- swap(&arr[j - div_len], &arr[j]);
- }
- }
- }
- void
- shellsort(int *arr, int arr_len)
- {
- int div = arr_len / 2;
- while (div > 0) {
- insertion_sort(arr, div, arr_len);
- div = div / 2;
- }
- }
- void
- swap(int *a, int *b)
- {
- int tmp;
- tmp = *a;
- *a = *b;
- *b = tmp;
- }
- void
- print_arr(int *arr, int arr_len)
- {
- int i = 0;
- while (i < arr_len) {
- printf("%d ", arr[i]);
- i++;
- }
- printf("\n");
- }
复制代码 |
|