本文为排序算法-希尔排序的代码实现。
作者水平比较差,有错误的地方请见谅。
1、希尔排序
希尔排序属于插入排序。
平均时间复杂度:比直接插入低。具体分体非常复杂,有兴趣可自行研究。
平局空间复杂度:O(1)。因为只在交换位置时使用一个辅助空间做暂存记录。
2、C#实现
ShellSort.cs
public static class ShellSort
{
public static void Shell(int[] numbers)
{
if (numbers == null || numbers.Length < 2)
{
Console.WriteLine("参数数组有误");
return;
}
//存储每次的增量值
int[] addArray = { 5, 3, 1 };
for (int i = 0; i < addArray.Length; i++)
{
//使用不同增量进行排序
ShellInsert(numbers, addArray[i]);
}
}
public static void ShellInsert(int[] numbers, int add)
{
for (int i = add; i < numbers.Length; i++)
{
//这里相当于直接插入排序,每次比较新加入的元素
//每个组的元素上一个元素index就是 -add
if (numbers[i] < numbers[i - add])
{
int temp = numbers[i];
int j;
//要保证数组不会越界
for (j = i; j > (i-add) && numbers[j - add] > temp; j -= add)
{
numbers[j] = numbers[j - add];
}
numbers[j] = temp;
}
}
for (int k = 0; k < numbers.Length; k++)
{
Console.Write(numbers[k] + " ");
}
Console.WriteLine();
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
int[] numbers = { 49, 38, 65, 97, 76, 13, 27, 49 };
ShellSort.Shell(numbers);
for (int i = 0; i < numbers.Length; i++)
{
Console.Write(numbers[i] + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
3、C++实现
ShellSort.cpp
///希尔排序
class ShellSort
{
public:
static void Shell(int numbers[],int length);
static void ShellInsert(int numbers[],int length,int add);
};
void ShellSort::Shell(int numbers[],int length)
{
if (numbers == NULL || length < 2)
{
cout<<"参数数组有误"<<endl;
return;
}
int addArray[] = {5,3,1};
for(int i=0;i<3;i++){
ShellInsert(numbers,length,addArray[i]);
}
}
void ShellSort::ShellInsert(int numbers[],int length,int add)
{
for(int i=add;i<length;i++){
if(numbers[i]<numbers[i-add]){
int temp = numbers[i];
int j;
for(j=i;j>(i-add)&&numbers[j-add]>temp;j-=add){
numbers[j] = numbers[j-add];
}
numbers[j] = temp;
}
}
for (int k = 0; k < length; k++)
{
cout << numbers[k] << " ";
}
cout << endl;
}
main.cpp
int main()
{
int numbers[] = {49,38,65,97,76,13,27,49};
int length = sizeof(numbers)/sizeof(numbers[0]);
ShellSort::Shell(numbers,length);
for(int i=0;i<length;i++){
cout<<numbers[i]<<" ";
}
cout<<endl;
return 0;
}
4、lua实现
numbers = {49, 38, 65, 97, 76, 13, 27, 49}
function ShellSort(nums)
local length = #nums
if (nums == nil or length < 2) then
print("参数数组有误")
return
end
local addArray = { 5, 3, 1 }
for i=1,#addArray,1 do
ShellInsert(nums, addArray[i])
end
end
function ShellInsert(nums,add)
for i=add+1,#nums,1 do
if (nums[i] < nums[i-add]) then
local temp = nums[i]
--这里相当于直接插入排序,每次比较新加入的元素
--每个组的元素上一个元素index就是 -add
for j=i,i-add,-add do
--要保证数组不会越界
if(j>i-add and nums[j-add]>temp) then
nums[j] = nums[j-add]
else
nums[j] = temp
break
end
end
end
end
for k=1,#nums,1 do
io.write(nums[k] .. ' ')
end
print()
end
ShellSort(numbers)
for i=1,#numbers,1 do
io.write(numbers[i] .. ' ')
end
print()
--#nums 获取数组长度