直接插入排序

来源:互联网 发布:乐乎lofter重口味 编辑:程序博客网 时间:2024/06/05 16:59

思想:(见图)


方法一:

直接上代码:

void InsertSort(int *a,int size){assert(a);int i, j, tmp;for (i = 0; i < size-1; ++i){tmp = a[i + 1];for (j = i; j >= 0; --j)   //在有序序列中插入后来数{if (a[j] > tmp){a[j+1] = a[j];}else{break;}}a[j+1] = tmp;//原来时上边的J最后又减了一个}}
方法二:

其实是一个有问题的程序,因为出现数组下标是负数了,源于功能能实现,所以摆放于此

//很可笑的一个问题void InsertSort(int *a,int size){assert(a);int i, j, tmp;for (i = 0; i < size-1; ++i){tmp = a[i + 1];for (j = i; j >= -1; --j){if (a[j] > tmp)          //[j] j尽然成负数了{a[j+1] = a[j];}else{a[j + 1] = tmp;break;}}}}
方法三:

//下面就是对的void InsertSort(int a[], int len){int i, j, temp;for (i = 1; i<len; i++){if (a[i]<a[i - 1]){temp = a[i];for (j = i - 1; a[j]>temp; j--)a[j + 1] = a[j];a[j + 1] = temp;}}}

方法四:

end为有序序列最后一个元素下标

void InsertSort(int *a, int size){assert(a);for (int i = 1; i < size; ++i){int index = i;int tmp = a[index];int end = index - 1;while (end >= 0 && tmp < a[end]){a[end + 1] = a[end];--end;}a[end + 1] = tmp; //这里end加一是因为上边多减得一个}}




1 0
原创粉丝点击