After several months of interviews, I recently read introduction to algorithms and want to use the algorithms in C ++ for implementation. Today is the first algorithm, which is relatively simple.
Chapter 2 Introduction to Algorithms
Insert sort
Pseudo-code implementation
Insertion-sort (a) Introduction to algorithms p10
1 for j ← 2 to length[A]2 do key ← A[j]3 //Insert A[j] into the sorted sequence A[1 ‥ j - 1].4 i ← j - 15 while i > 0 and A[i] > key6 do A[i + 1] ← A[i]7 i ← i - 18 A[i + 1] ← key
C ++ code implementation
1 #include <iostream> 2 3 using namespace std; 4 5 void insertSort(int *arr, int n) 6 { 7 int i, j, key; 8 for(j = 1; j < n; j++) 9 {10 key = arr[j];11 i = j - 1;12 while((i >= 0) && (arr[i] > key))13 {14 arr[i + 1] = arr[i];15 i--;16 }17 arr[i + 1] = key;18 }19 }20 21 int main()22 {23 int a[] = {2, 4, 32, 64, 67, 34, 78, 23, 3456, 2345, 123, 1, 3};24 insertSort(a, 13);25 for(int i = 0; i < 13; i++)26 {27 cout << a[i] << " ";28 }29 cout << endl;30 return 0;31 }
I hope I can stick to it all the time.