开发者

classwork - shellsort in c#?

i need an easy way to sort an array using ShellS开发者_StackOverflowort in c#, please help me


Use shell sort.


Nobody is going to write your code for you. You're there to learn. I'd take the following steps:

  1. Go to Wikipedia's Shell Sort Page

  2. Find the psuedocode for the algorithm. Read it until you understand what it does.

  3. Port the psuedocode to C#.

  4. If you have a problem during implementation feel free to come back and ask specific questions.


    public static int[] shellSort(int[] ar)
    {
        //this gaps array works but is not unique
        int[] gaps = new int[] { 1, 4, 10, 23, 57, 132, 301, 701 };
        gaps = gaps.Reverse().ToArray();

        Func<int, int, bool> potentialSwitch = (ind1, ind2) =>
        {
            if (ar[ind2] < ar[ind1])
            {
                int temp = ar[ind2];
                ar[ind2] = ar[ind1];
                ar[ind1] = temp;
                return true;
            }
            return false;
        };

        foreach (int gap in gaps)
        {
            if (gap >= ar.Length)
                continue;

            for (int i = 0; i + gap < ar.Length; i++)
            {
                int j = i;
                while (potentialSwitch(j, j + gap))
                {
                    j -= gap;
                    if (j < 0)
                        break;
                }
            }
        }

        return ar;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜