您的位置:首页 > 理论基础 > 数据结构算法

数据结构算法之排序系列Java、C源码实现(1)--直接插入排序

2016-02-27 11:05 459 查看
使用插入排序,对于具有n个记录的文件,要进行n-1趟排序,是稳定的插入排序。

直接插入排序:从未排序的序列中依次取出一个元素与已排序列中的元素进行比较,然后将其放在已排序序列的合适位置上。

思想宗旨就是将无序的数据向有序的数据中插入 ,默认选择比较的元素是有序序列的最大值开始比较(高级一点的算法,可以采用

二分查找)来选取这个开始比较的元素

实际就是有序元素和temp变量比较不断移动的过程

java代码:

public class Insert_sort {
public static void main(String[] args) {
int array[] = {2,10,4,5,1,8};
showArray(array);
System.out.println("\n排序后");
insert_sort(array);
showArray(array);
}

private static void insert_sort(int[] a) {
int temp;
int j;
for(int i=1;i<a.length;i++)
{
temp = a[i];
j = i-1;
while(j>=0 && temp<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1] = temp;
}
}

private static void showArray(int[] a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
}

C代码:

//直接插入排序 
#include<stdio.h>

void showArray(int a[],int len)
{
for(int i=0;i<len;i++)
{
printf("%d ",a[i]);
}
}

void insert_sort(int a[],int n)
{
int temp;
int j;
for(int i=1;i<n;i++)
{
temp = a[i];
j = i-1;
while(j>=0 && temp<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1] = temp;
}
}

int main()
{
int array[] = {2,10,4,5,1,8};
int len = sizeof(array)/sizeof(int);
showArray(array,len);
printf("\n排序后\n");
insert_sort(array,len);
showArray(array,len);
return 0;
}

直接插入排序是插入排序的一种 时间复杂度最好情况是O(n),是待排序列都是有序的,不需要移动

最坏是O(n^2),待排序列是逆序,平均情况是O(n^2),直接插入排序是一种稳定的排序,辅助存储空间O(1) 有一个temp变量临时存储
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息