排序算法,冒泡排序,选择排序,插入排序
chunli@CentOS/tmp/work$ cat sort.c #include#include #include int bubble_sort(int array[], int size){ if(NULL == array || size <2) { return -1; } int i = 0; int j = 0; for(i = 0; i < size; i++) { for(j = 0; j < size; j++) { if(array[i] < array[j]) { int t = array[i]; array[i] = array[j]; array[j] = t; } } } return 0;}int select_sort(int array[], int size){ if(NULL == array || size <2) { return -1; } int i = 0; int j = 0; int index = 0; for(i=0; i < array[index]) { index = j; } } int tmp = array[i]; array[i] = array[index]; array[index] = tmp; } return 0;}int insert_sort(int array[], int size){ if(NULL == array || size <2) { return -1; } int i = 0; int j = 0; int t = 0; for(i=1; i array[i]) { t = array[i]; j = i; while(j>0 && array[j-1]>t) { array[j] = array[j-1]; j--; } array[j] = t; } } return 0;}int main(){ srand((int)time(NULL)); int array[30]; for(int i=0;i
二分查找:
chunli@CentOS/tmp/work$ cat sort.c #include#include #include int bubble_sort(int array[], int size){ if(NULL == array || size <2) { return -1; } int i = 0; int j = 0; for(i = 0; i < size; i++) { for(j = 0; j < size; j++) { if(array[i] < array[j]) { int t = array[i]; array[i] = array[j]; array[j] = t; } } } return 0;}int binaray(int array[], int size, int key){ int low = 0; int high = size; int mid = 0; while(low <= high) { mid = (high+low)/2; if(key == array[mid]) { return mid; } else if(key > array[mid]) { low = mid+1; } else { high = mid-1; } } return -1;} int main(){ srand((int)time(NULL)); int array[30]; int ret = 0; for(int i=0;i
二分查找,递归实现
chunli@CentOS/tmp/work$ cat sort.c #include#include #include int bubble_sort(int array[], int size){ if(NULL == array || size <2) { return -1; } int i = 0; int j = 0; for(i = 0; i < size; i++) { for(j = 0; j < size; j++) { if(array[i] < array[j]) { int t = array[i]; array[i] = array[j]; array[j] = t; } } } return 0;}int binaray(int array[], int IndexLow, int IndexHigh, int key){ if(NULL == array) { return -1; } if(IndexLow <= IndexHigh) { int IndexMid = (IndexLow + IndexHigh)/2; if(array[IndexMid] == key) { return IndexMid; } else if(key > array[IndexMid]) { return binaray(array, IndexMid+1, IndexHigh, key); } else { return binaray(array, IndexLow, IndexMid-1, key); } } return -1;}int main(){ srand((int)time(NULL)); int array[31]; int ret = 0; for(int i=0;i