排序与查找
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
- 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
- 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; }
轉(zhuǎn)載于:https://my.oschina.net/kimiz/blog/195997
總結(jié)
- 上一篇: linux+apache+mysql+p
- 下一篇: Java保留小数点一位的方法