【算法】 分治
二分查找
#include<stdio.h> void sort(int *a , int n) { int temp = 0 ; for(int i = 0 ; i < n ; i++) { for(int j = 0 ; j < n ; j++ ) if(a[j] > a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } if(temp == 0) break; } } int BinarySearch(int *a , int high , int data) { int low = 0; int mind = (low + high)/2; while(low <= high) { if(a[mind] == data) return mind; if(a[mind] > data) high = mind - 1 ; if(a[mind] < data ) low = mind + 1; mind = (low + high)/2 ; } return -1 ; } int BinarySearchDG(int *a , int high , int low , int data) { mind = (low + high) / 2 ; if(a[mind] == data) return -1; if(a[mind] > data) BinarySearchDG(a , high , mind + 1 , data); if(a[mind] < data) BinarySearchDG(a , mind - 1 , low , data); } void printOut(int *a , int n ) { int i = 0; while(i < n) printf("%d\n", a[i++]); } int main() { int a[] = {18,26,3,4,5,60,56,37}; sort(a , 8); printOut(a , 8 ); int m = BinarySearch(a , 8 , 18); printf("%d" , m ); }
归并排序
#include<stdio.h> void PrintSort(int *a , int high) { int i = 0 ; while(i <= high) { printf("%d---\n" , a[i++]); } } void Merge(int *a , int low , int mind , int high) { int *b = new int[high - low + 1]; int h = 0 , i , j , k = 0; for( i = low , j = mind + 1 ; i <= mind && j <= high ; ) { if(a[i] >= a[j]) b[h++] = a[i++]; else b[h++] = a[j++]; } while( j <= high ) { b[h++] = a[j++]; } while( i <= mind ) { b[h++] = a[i++]; } h = low ; while(h <= high) a[h++] = b[k++]; } void MergeSort(int *a , int low , int high) { int mind ; if(high > low) { mind = (low + high) / 2; MergeSort(a , low , mind); MergeSort(a , mind+1 , high); Merge(a , low , mind , high); } } int main () { int a[] = {1,2,1,2,3,5,6}; MergeSort(a , 0 , 6); PrintSort(a , 6); }
快速排序
#include<stdio.h> void swap( int &a1 , int &a2 ) { int data; data = a1; a1 = a2 ; a2 = data; } int Partition(int *a , int low , int high) { // 划分方法,每次划分后使 int pivot = a[low] , i , j ; for( i = low , j = high ; i < j ; ) { //pivot = a[low] 处于该数组的最终位置 while(a[j] >= pivot && j > i ) //若尾部元素大于指针元素,则继续向前移动 j-- j--; if( j > i ) swap(a[i++] , a[j]); while(a[i] < pivot && j > i ) //若首部元素小于指针元素,则向后移动 i++ i++; if( j > i ) swap(a[j--] , a[i]); } return j ; } void QuickSort(int *a , int low , int high) { //递归,不断将问题进行划分 ,化成更小的问题 int index; if(low < high) { //判断是否到达栈低 index = Partition( a , low , high); QuickSort( a , low , index - 1 ); QuickSort( a , index + 1 , high); } } void PrintArray(int *a , int n) { for(int i = 0 ; i < n ; ) printf(" %d " , a[i++]); printf("\n"); } int main() { int a[10] = {1,55,6,5,4154,5,46546,787846,775}; PrintArray(a , 10); QuickSort(a , 0 , 9); PrintArray(a , 10); }