算法在计算机科学领域中占有举足轻重的地位,一套算法设计的好坏直接决定了一项工程的成败。在大学教育中老师就教导我们要数据结构 + 算法(现在还需要加上体系结构吧),但是这两门基础课我却从没有学好过:)我打算来个周记,每周仔细研究一个算法,然后分别用C#、Java、Matlab实现,供感兴趣的朋友一起学习、研究。除了常见的算法分类之外,我会格外关注数值算法,因为我对数学有着浓厚的兴趣。由于我C++学的不好,故不提供C++算法实现,具体C++的资料很多,感兴趣的朋友可以多查找下。
测试环境:
Windows Server 2008 R2 DataCenter
C#:Visual Studio 2010 Ultimate RC(.NET Framework 4.0 RC x64)
Java:Eclipse SDK 3.5.1 x64(JDK 1.6 Update 18 x64)
Matlab:Matlab R2009b x64
PS(Visual Studio 2010正式版即将发布,到时会更新;Matlab R2010a已经发布,正在测试,近期也会更新)
直接插入排序
基本思想:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的记录中的适当位置,直到全部记录插入完成为止。
直接插入排序是把一个序列分为两部分,第一部分是排好序的,数学上叫做"有序区",然后从第二个部分中("无序区")将第一个记录插入到有序区中,使得插入后有序区仍然有序。然后重复上述操作,每次无序区均减少一个记录,直至其中记录数为零。
复杂度:时间复杂度为O(N^2),空间复杂度为O(1)。
可以看出,N^2还是很大的,当N较大时,不宜采用直接插入排序。推荐记录的数目是N<20。
C#语言描述:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InsertSort
{
class InsertSortDemo
{
private static int [] fxInsertSort( int [] arr)
{
int i, j, arrTmp;
for (i = 1 ; i < arr.Length; i ++ )
{
j = i;
arrTmp = arr[i];
while (j > 0 && arr[j - 1 ] > arrTmp)
{
arr[j] = arr[j - 1 ];
j -- ;
}
arr[j] = arrTmp;
}
return arr;
}
static void Main( string [] args)
{
int [] arr = InsertSortDemo.fxInsertSort( new int [] { 1 , 4 , 2 , 6 , 5 });
foreach ( int i in arr)
{
Console.Write(i + " , " );
}
Console.ReadLine();
}
}
}
Java语言描述:
public class InsertSortDemo {
/**
* @param args
*/
private static int [] fxInsertSort( int [] arr) {
int i, j, arrTmp;
for (i = 1 ; i < arr.length; i ++ ) {
j = i;
arrTmp = arr[i];
while (j > 0 && arr[j - 1 ] > arrTmp) {
arr[j] = arr[j - 1 ];
j -- ;
}
arr[j] = arrTmp;
}
return arr;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] arr = InsertSortDemo.fxInsertSort( new int [] { 1 , 4 , 2 , 6 , 5 });
for ( int i = 0 ; i < arr.length; i ++ ) {
System.out.print(arr[i] + " , " );
}
}
}
Matlab语言描述:
arr = [ 1 4 2 6 5 ] ;
% Matlab中数组索引从1开始
for i = 2 :length ( arr )
j = i ;
arrTmp = arr ( i );
while j > 1 && ( arr ( j - 1 ) > arrTmp )
arr ( j ) = arr ( j - 1 );
j = j - 1 ;
end
arr ( j ) = arrTmp ;
end
% 输出排序后结果
disp ( arr );