博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Gnome sort

Posted on 2009-12-19 17:32  smallnest  阅读(253)  评论(0编辑  收藏  举报

类别:排序-交换排序
参看 维基百科的定义

Gnome sort is a sorting algorithm which is similarto insertion sort, except that moving an element to its proper place isaccomplished by a series of swaps, as in bubble sort. The name comesfrom the supposed behavior of the Dutch garden gnome in sorting a lineof flowerpots and is described on Dick Grune's Gnome sort page.

1 using System;
2  using System.Collections.Generic;
3
4 namespace Com.Colobu.Algorithm.Exchange
5 {
6 /// <summary>
7 /// <b>Gnome sort</b> is a sorting algorithm which is similar to insertion sort,
8 /// except that moving an element to its proper place is accomplished
9 /// by a series of swaps, as in bubble sort.
10 /// Gnome Sort is based on the technique used by the standard Dutch Garden Gnome.
11 /// Here is how a garden gnome sorts a line of flower pots.
12 /// Basically, he looks at the flower pot next to him and the previous one;
13 /// if they are in the right order he steps one pot forward,
14 /// otherwise he swaps them and steps one pot backwards.
15 /// Boundary conditions: if there is no previous pot,
16 /// he steps forwards; if there is no pot next to him, he is done.
17 ///
18 /// 平均时间复杂度:O(n^2)
19 /// Stability:Yes
20 /// </summary>
21 public class GnomeSortAlgorithm
22 {
23 public static void GnomeSort<T>(IList<T> szArray) where T : IComparable
24 {
25 int i = 1;
26 int j = 2;
27 int count = szArray.Count;
28 while (i < count)
29 {
30 if (szArray[i - 1].CompareTo(szArray[i]) < 0) //for descending sort, reverse the comparison to >=
31 {
32 i = j;
33 j = j + 1;
34 }
35 else
36 {
37 Swap(szArray, i - 1, i);
38 i = i - 1;
39 if (i == 0)
40 {
41 i = j;
42 j = j + 1;
43 }
44 }
45 }
46 }
47 private static void Swap<T>(IList<T> szArray, int i, int j)
48 {
49 T tmp = szArray[i];
50 szArray[i] = szArray[j];
51 szArray[j] = tmp;
52 }
53 }
54 }
55