# 希爾排序

• 第1步：以扁平形式排列元素，並使用插入排序對列進行排序。
• 第2步：重複第1步; 每次使用較少數量的較長列，最終只需要對一列資料進行排序。

#### 複雜性

``````Shell_Sort(Arr, n)

SWAP Arr[I + GAP_SIZE], Arr[I]
SET FLAG = 0

``````

``````#include <stdio.h>
void shellsort(int arr[], int num)
{
int i, j, k, tmp;
for (i = num / 2; i > 0; i = i / 2)
{
for (j = i; j < num; j++)
{
for(k = j - i; k >= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
break;
else
{
tmp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = tmp;
}
}
}
}
}
int main()
{
int arr[30];
int k,  num;
printf("Enter total no. of elements : ");
scanf("%d", &num);
printf("Enter %d numbers: ", num);

for (k =  0 ; k < num; k++)
{
scanf("%d", &arr[k]);
}
shellsort(arr, num);
printf("Sorted array is: ");
for (k = 0; k < num; k++)
printf("%d ", arr[k]);
return 0;
}
``````

``````Enter total no. of elements : 6
3
2
4
10
2
1

Sorted array is: 1 2 2 3 4 10
``````

``````import java.util.*;
public class Shell_Sort
{
static void shellsort(int[] arr, intnum)
{
int i, j, k, tmp;
for (i = num / 2; i> 0; i = i / 2)
{
for (j = i; j<num; j++)
{
for(k = j - i; k>= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
break;
else
{
tmp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = tmp;
}
}
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int arr[]= newint[30];
intk,  num;
System.out.println("Enter total no. of elements : ");
num = sc.nextInt();
for (k =  0 ; k<num; k++)
{
arr[k]=sc.nextInt();
}
shellsort(arr, num);
System.out.println("\n Sorted array is: ");
for (k = 0; k<num; k++)
System.out.println(arr[k]);
}
}
``````

``````Enter total no. of elements : 6
3
2
4
10
2
1

Sorted array is: 1 2 2 3 4 10
``````

``````using System;
public class Shell_Sort
{
static void shellsort(int[] arr, int num)
{
int i, j, k, tmp;
for (i = num / 2; i > 0; i = i / 2)
{
for (j = i; j < num; j++)
{
for(k = j - i; k >= 0; k = k - i)
{
if (arr[k+i] >= arr[k])
break;
else
{
tmp = arr[k];
arr[k] = arr[k+i];
arr[k+i] = tmp;
}
}
}
}
}
public void Main()
{
int[] arr=new int[10];
int k,  num;
Console.WriteLine("Enter total no. of elements : ");
for (k =  0 ; k < num; k++)
{
}
shellsort(arr, num);
Console.WriteLine("\n Sorted array is: ");
for (k = 0; k < num; k++)
Console.WriteLine(arr[k]);
}
}
``````

``````Enter total no. of elements : 6
3
2
4
10
2
1

Sorted array is: 1 2 2 3 4 10
``````