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 }