C#实现:插入排序
算法描述
一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
1. 从第一个元素开始,该元素可以认为已经被排序
2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
5. 将新元素插入到该位置中
6. 重复步骤2
public void sort(int[] data, int len)
{
for (int i=1; i<len; i++)
{
int key = data[i];
int j=i-1;
while(j>=0 && data[j]>key)
{
data[j+1]=data[j];
j--;
}
data[++j]=key;
}
}
{
for (int i=1; i<len; i++)
{
int key = data[i];
int j=i-1;
while(j>=0 && data[j]>key)
{
data[j+1]=data[j];
j--;
}
data[++j]=key;
}
}
本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.
浙公网安备 33010602011771号