插入排序
- #include <iostream>
-
- #define SIZE 10
-
- void insert(int list[], int size);
-
- int list_size[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
-
- using namespace std;
-
- int main()
- {
- insert(list_size, SIZE);
- cout << endl;
- return 0;
- }
-
- void insert(int list[], int size) {
- int key = 0;
- int i = 0, j = 0, count = 0;
- for(j = 1; j < size; j++) {
- key = list[j];
- for(i = j - 1; i >= 0 && list[i] > key; i--, count++){
- list[i + 1] = list[i];
- }
- list[i + 1] = key;
- }
- for(int k = 0; k < size; k++) {
- cout << " " << list[k];
- }
- cout << endl << "loop count: " << count;
- }
递归查最大值
- #include <iostream>
-
- using namespace std;
-
- #define MAX(x,y) \
- x > y ? x : y;
-
- int mArray[] = {1,4,2,5,22,545,52,42,545,45,3,45,24,47,2,54,781,2,453,42,45,33,42,20,456,454,352,4,24111,234,5,13,435,165,35,435,435,435,435,1,43,6,13,434,3,4};
-
- int findMax(int *array, int size) {
- cout <<"Array:" << array <<"findMax size:" << size << endl;
- if(size == 2) {
- return MAX(array[0], array[1])
- } else if (size == 1) {
- return array[0];
- } else {
- return MAX(findMax(&array[0], size/2), findMax(&array[size/2 + 1], size - (size/2 + 1)));
- }
- }
-
- int main() {
- int max = 0;
- int size = sizeof(mArray)/sizeof(int);
- max = findMax(mArray, size);
- cout << "max: " << max << " size:" << size << endl;
- return 1;
- }