直接插入排序

直接插入排序

直接插入排序是每次把无序序列中的第一个元素,然后插入到有序序列的合适位置,即排序过程中会出现两部分,一部分是已排序的有序序列,还有一部分是待排序的无序序列。

排序过程通过一个二重循环实现。外层循环确定下一个待排序的值,即无序序列的第一个元素,内层循环实现对待排序元素插入位置的查找。

 

直接插入排序C++实现:



/****************************
 *Name:直接插入排序.cpp
 *Tags:排序
 *Note:
 *****************************/

#include <iostream>
#define MAX_SIZE 1000
using namespace std;

int InsertSort(int *, int, int);

int main()
{
      int array[MAX_SIZE];
      int len, i;
      cout << "Input the length of the array: ";
      cin >> len;
      for(i = 0; i < len; i++) {
	    cin >> array[i];
      }
      InsertSort(array, 0, len); //简单插入排序
      cout << "The result of the Insertion Sort:" << endl;
      for(i = 0; i < len; i++) {
	    cout << array[i] << " ";
      }
      cout << endl;
      return 0;
}

int InsertSort(int *array, int start, int end)
{
      int temp, i, j;
      for(i = start+1; i < end; i++) {
	    temp = array[i];
	    j = i;
	    while(j > start && array[j-1] > temp) {
		  array[j] = array[j-1];
		  j--;
	    }
	    array[j] = temp;
      } //排序过程
      return 0;
}		  

直接插入排序的时间复杂度为O(n^2),直接插入排序是一个稳定的排序算法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值