1. 程式人生 > >常見排序之希爾排序

常見排序之希爾排序

#include <stdio.h> 

#include <stdlib.h> 

void ShellSort(int a[], int length) 

    int increment; 

    int i,j; 

    int temp; 

    for(increment = length/2; increment > 0; increment /= 2) //用來控制步長,最後遞減到1 

    { 

        // i從第step開始排列,應為插入排序的第一個元素 

        // 可以先不動,從第二個開始排序 

        for(i = increment; i < length; i++) 

        { 

            temp = a[i]; 

            for(j = i - increment; j >= 0 && temp < a[j]; j -= increment) 

            { 

                a[j + increment] = a[j]; 

            } 

            a[j + increment] = temp; //將第一個位置填上 

        } 

    } 

 

int main() 

    printf("==============希爾排序===============\n\n"); 

    int i, j; 

    int a[] = {5, 18, 151, 138, 160, 63, 174, 169, 79, 200};     

    printf("待排序的序列是: \n"); 

    for(i = 0; i < 10; i++) 

    { 

        printf("%d ", a[i]); 

    } 

    ShellSort(a, 10); 

    printf("\n排序後的序列是: \n"); 

    for(j = 0; j < 10; j++) 

    { 

        printf("%d ", a[j]); 

    } 

    printf("\n"); 

    return 0; 

 

方法二:

#include<stdio.h>

#include<stdlib.h>

 

 

void ShellSort(int *array,int length)

{

      int i,j,temp,increment;

 

      increment = length;

 

      do

      {

           increment /= 2;

 

           for(i = increment; i < length; i++)

           {

                

                 //if(array[i] < array[i-increment])

                 {

                      temp = array[i];

 

                      for(j = i-increment; j >= 0 && array[j] > temp; j -= increment)

                      {

                            array[j+increment] = array[j];

                      }

 

                      array[j+increment] = temp;

                 }

                     

                

           }

 

      }

      while(increment > 0);

}

 

int main(void)

{

      int i;

 

      int Array[5] = {4,2,1,5,3};

 

     

      ShellSort(Array,5);

 

      for(i = 0; i < 5; i++)

      {

           printf("%d ",Array[i]);

      }

      return 0;

}