希尔排序

#include<stdio.h>
#include<stdlib.h>

void shell_sort(int v[], int n);
void printarray(int a[], int n);

main(void)
{
    int a[5] = {5,4,3,2,1};
    shell_sort(a, 5);
}

/*shell sort: increment*/
//add some printf to analysis process
void shell_sort(int v[], int n)
{
    int gap, i, j, temp;
    
    for(gap = n/2; gap > 0; gap /= 2) {
        printf("\ngap = %d\t\tV[j] - V[j+gap]\n", gap);
        for(i = gap; i < n; i++){
            printf("i = %d\t\t", i);
            for(j = i-gap; j>=0; j-=gap) {
                if(v[j]>v[j+gap]) {
                temp = v[j];
                v[j] = v[j+gap];
                v[j+gap] = temp;
                }
                printf("[%2d]-[%2d]  ", j, j+gap);
            }
            printf("\n");
        }
    printf("after gap(%d):", gap);        //打印每趟排序后的结果
    printarray(v, n);
    }        
}

void printarray(int a[], int n)
{
  int i;
  for (i = 0; i < n; i++)
    printf(" %d", a[i]);
  printf("\n");
}


/* without analysis
void shell_sort(int v[], int n)
{
    int gap, i, j, temp;
    
    for(gap = n/2; gap > 0; gap /= 2)
        for(i = gap; i < n; i++)
            for(j = j-gap; j>=0 && v[j]>v[j+gap]; j-=gap) {
                temp = v[j];
                v[j] = v[j+gap];
                v[j+gap] = temp;
            }
}
*/


你可能感兴趣的:(希尔排序)