数据结构--插入排序

﹏ヽ暗。殇╰゛Y 2022-07-28 10:53 269阅读 0赞

算法中经常会用到各种各样的算法,比较简答的思想就是冒泡排序,一般刚开始编程时遇到排序问题时,会很容易想到冒泡排,冒泡排序是通过两辆比较数值,从而将数字移动到开始或者末尾的位置,反复重复这个过程从而就达到了排序的目的。其时间复杂度大概是Ο(n2)。还有一种比较常用的插入排序,其思想与冒泡排序比较类似。下面来逐步讲解插入排序的思想:

1、首先考虑到将一个数字插入到一个有序表中,这里有序表代表可以是非增序列,也可以是非减序列。插入完成后,该有序表仍然保持原有的特性。

对于这种情况下,实现的C++代码是:

  1. /**
  2. @para: sorted_array: 有序表
  3. element: 需要插入的元素
  4. length: 有序表在没有插入元素时的原始长度
  5. @function: 实现插入排序
  6. */
  7. template<class T>
  8. void Insert(T *sorted_array, const T &element, int length)
  9. {
  10. //sorted_array[0:length-1] is ordered array and is in increasing order
  11. int cnt = length;
  12. while (element<sorted_array[cnt] && cnt>=0)
  13. {
  14. sorted_array[cnt + 1] = sorted_array[cnt];
  15. cnt--;
  16. }
  17. sorted_array[cnt + 1] = element;
  18. }

2、紧接着我们考虑迭代的过程,对于一个长度为length的序列,从分别对其部分长度为1,2,……,一直到length的序列进行插入,插入的数字即该长度范围外的第一个数字,即对序列sorted_array[0]开始插入数字sorted_array[1],sorted_array[2]。。。。

最后得到的序列保持了在第一步进行过程中的有序性,因此最后得到的序列是有序的,实现过程是:

  1. template<class T>
  2. void InsertOrder(T *sorted_array, int length)
  3. {
  4. for (int i = 1; i<length; i++)
  5. {
  6. T temp = sorted_array[i];
  7. Insert(sorted_array, temp, i - 1);
  8. }
  9. }

3、最后的完整实现过程是:

  1. #include <iostream>
  2. using namespace std;
  3. /**
  4. @para:sorted_array: 有序表
  5. element: 需要插入的元素
  6. length: 有序表在没有插入元素时的原始长度
  7. @function: 实现插入排序
  8. */
  9. template<class T>
  10. void Insert(T *sorted_array, const T &element, int length)
  11. {
  12. //sorted_array[0:length-1] is ordered array and is in increasing order
  13. int cnt = length;
  14. while (element<sorted_array[cnt] && cnt>=0)
  15. {
  16. sorted_array[cnt + 1] = sorted_array[cnt];
  17. cnt--;
  18. }
  19. sorted_array[cnt + 1] = element;
  20. }
  21. template<class T>
  22. void InsertOrder(T *sorted_array, int length)
  23. {
  24. for (int i = 1; i<length; i++)
  25. {
  26. T temp = sorted_array[i];
  27. Insert(sorted_array, temp, i - 1);
  28. }
  29. }
  30. int main()
  31. {
  32. int length ;
  33. cout<<"please input the length of array being sorted:";
  34. cin>>length;
  35. int *sorted_array;
  36. sorted_array = new int[length];
  37. cout<<"input the array and the separate with numbers with space:"<<endl;
  38. for (int i = 0; i<length; i++)
  39. {
  40. cin >> sorted_array[i];
  41. }
  42. InsertOrder(sorted_array, length);
  43. for (int i = 0; i<length; i++)
  44. {
  45. cout << sorted_array[i] << " ";
  46. }
  47. return 0;
  48. }

4、最后我们来看看插入排序的每次插入的过程:
20160414203509394

发表评论

表情:
评论列表 (有 0 条评论,269人围观)

还没有评论,来说两句吧...

相关阅读

    相关 数据结构--插入排序

    算法中经常会用到各种各样的算法,比较简答的思想就是冒泡排序,一般刚开始编程时遇到排序问题时,会很容易想到冒泡排,冒泡排序是通过两辆比较数值,从而将数字移动到开始或者末尾的位置,

    相关 数据结构插入排序

    插入排序的基本思想是:每步将一个待排序的对象,按其关键字大小,插入到前面已经排好序的一组对象的适当位置上,直到对象全部插入为止。 简言之,边插入边排序,保证子序列中随时都是排

    相关 数据结构--直接插入排序

    直接插入排序 概念 插入排序的基本思想是:在一个已排好序的记录子集的基础上,每一步将下一个待排序的记录有序地插入到已排好序的记录子集中,直到将所有待排记录全部插入为