ソート6:ヒルソート

7108 ワード

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ShellSort
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int[] arr = new int[10];
14             Random rd = new Random();
15             for (int i = 0; i < arr.Length; i++)
16             {
17                 //arr[i] = rd.Next(10);
18                 arr[i] = arr.Length - i;
19             }
20             ShellSort(arr);
21             foreach (int i in arr)
22                 Console.WriteLine(i);
23         }
24 
25         public static void ShellSort(int[] arr)
26         {
27             int temp, k;
28             int len = arr.Length / 2;
29             for (int gap = len; gap > 0; gap /= 2)
30             {
31                 for (int j = gap; j < arr.Length; j++)
32                 {
33                     temp = arr[j];
34                     k = j - gap;
35                     while (k >= 0 && arr[k] > temp)
36                     {
37                         arr[k + gap] = arr[k];
38                         k -= gap;
39                     }
40                     arr[k+gap] = temp;
41                 }
42             }
43         }
44 
45         public static void Swap(int[] arr, int a, int b)
46         {
47             int temp = arr[a];
48             arr[a] = arr[b];
49             arr[b] = temp;
50         }
51     }
52 }