为什么80%的码农都做不了架构师?>>>
- sort.h
#ifndef SORT_H_INCLUDED
#define SORT_H_INCLUDEDvoid bubble_sort(int a[], int len);void select_sort(int a[], int len);#endif // SORT_H_INCLUDED
- sort.cpp
#include "sort.h"void bubble_sort(int a[], int len)
{int tmp;for (int i = 0; i < len-1; ++i){for (int j = i+1; j < len; ++j){if ( a[i] > a[j] ){tmp = a[j];a[j] = a[i];a[i] = tmp;}}}
}void select_sort(int a[], int len)
{int min;int tmp;for (int i = 0; i < len-1; ++i){min = i;for (int j = i+1; j < len; ++j){if ( a[min] > a[j] ){min = j;}}if (min != i){tmp = a[min];a[min] = a[i];a[i] = tmp;}}
}
- search.h
#ifndef SEARCH_H_INCLUDED
#define SEARCH_H_INCLUDEDint binary_search(int *a, int len, int value);#endif // SEARCH_H_INCLUDED
- search.cpp
#include "search.h"int binary_search(int *a, int len, int value)
{int low;int mid;int high;low = 0;high = len - 1;while (low <= high){mid = (low + high) / 2;if (a[mid] < value){low = mid + 1;}else if (a[mid] > value){high = mid - 1;}else{return mid;}}return -1;
}
- main.cpp
#include <iostream>
#include <cstdlib>
#include <cstdio>#include "sort.h"
#include "search.h"using namespace std;int main()
{int a[] = {3, 1, 7, 6, 4, 10, 9};int len = sizeof(a)/sizeof(int);for (int i = 0; i < len; ++i){printf("%d\t", a[i]);}printf("\n");select_sort(a, len);for (int i = 0; i < len; ++i){printf("%d\t", a[i]);}printf("\n");int value1 = 6;int index = binary_search(a, len, value1);std::cout << index << std::endl;return 0;
}