Algorithmic Implementation series(1)——Implementation of Insertion_sort

本文介绍了一种基于C++的插入排序算法实现方法,并通过实际代码展示了如何对整型数组进行排序。该实现遵循《算法导论》第三版中描述的伪代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Complier: gcc 4.7.3 

Std: c++0x

Hi, everyone. I'd like to start my algorithmic implementation series in which I implement the algorithms based on the pseudo codes in 《Introduction to Algorithms》(3rd edition) as practices for both C++ programming and algorithms. My English isn't good enough to express my thought clearly sometimes, but I still choose English as the written language, so that I can be adapted to it. Suggestions to my implementations or better implementations are prefered. Thank you. :-)

Here's my implementation of Insertion_sort, there're some restrictions in my implementation, e.g. the element type of the array to be sorted. I'll try to improve it in the future.

  1 #include <iostream>
  2 #include <vector>
  3 
  4 using namespace std;
  5                                                                                               
  6 void INSERTION_SORT(int ia[], size_t size) {
  7     //If the size of vector ia is 0 or 1, 
  8     //return vector ia itself.
  9     //size_t size = sizeof(ia)/sizeof(int); 
 10     cout << "size of array is: " << size << endl;
 11     if(size == 0 || size == 1) {
 12         return;
 13     }
 14 /*
 15     for(size_t k = 0; k != size - 1; ++k){
 16         ia[k] *= 2;
 17     }
 18 */
 19 
 20     for(size_t j = 1; j != size; ++j) {
 21     //Storing the element at (j-1)th position in vector ia;
 22         int key = ia[j];
 23 
 24         cout << "key is: " << key << endl;
 25         int i = j - 1;
 26         while(i >= 0 && ia[i] > key) {
 27             ia[i + 1] = ia[i];
 28             i = i - 1;
 29         }
 30         ia[i + 1] = key;
 31         cout << "==============" << endl;
 32         for(auto i = 0; i < size; ++i) {
 33             cout << ia[i] << endl;
 34         }
 35     }
 36 }
 37 
 38 
 39 template <typename T>
 40 void show_array(T &ia) {
 41     for(auto t : ia) {
 42         cout << t << endl;
 43     }
 44 }
 45 
 46 int main() {
 47     int arr[6] = {5, 2, 4, 6, 1, 3};
 48     show_array(arr);
 49 
 50     INSERTION_SORT(arr, sizeof(arr)/sizeof(int));
 51 
 52     show_array(arr);
 53 
 54     return EXIT_SUCCESS;
 55 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值