1

i need an easy way to sort an array using ShellSort in c#, please help me

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Arthur
  • 11
  • 2
  • See for reference: [java implementation](http://stackoverflow.com/questions/12767588/time-complexity-for-shell-sort) – nawfal Jun 15 '14 at 07:40

3 Answers3

10

Use shell sort.

ncases
  • 101
  • 3
9

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.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
  • 4
    4. If you have a problem during implementation feel free to come back and ask specific questions. – Donnie Dec 14 '10 at 14:56
0
    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;
    }
Lee.O.
  • 63
  • 5