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:
Go to Wikipedia's Shell Sort Page
Find the psuedocode for the algorithm. Read it until you understand what it does.
Port the psuedocode to C#.
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;
}
精彩评论