// test21.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int bin_search(int * a,int low,int high,int target){//标准的二分查找 int mid; while(low<=high){ mid=low+(high-low)/2; if(target>a[mid]) low=mid+1; else if(target<a[mid]) high=mid-1; else return mid; } return NULL; } int partition(int * a,int low ,int high){//快排中的分划交换部分 int temp=a[low]; while(low<high){ while(low<high&&a[high]>=temp) high--; a[low]=a[high]; while(low<high&&a[low]<=temp) low++; a[high]=a[low]; } a[low]=temp; return low; } void quick_sort(int *a,int low, int high){//快排 if(low<high){ int mid=partition(a,low,high); quick_sort(a,low,mid-1); quick_sort(a,mid+1,high); } } void quick_sort1(int * a,int low,int high){//递归的快排 int temp=a[low]; int low1=low, high1=high; while(low1<high1){ while(low1<high1&&a[high1]>=temp) high1--; a[low1]=a[high1]; while(low1<high1&&a[low1]<=temp) low1++; a[high1]=a[low1]; } a[low1]=temp; if(low1<high) quick_sort1(a,low1+1,high); if(low<low1) quick_sort1(a,low,low1-1); } void bubble_sort(int * a,int len){//起泡排序; for(int i=len;i>0;i--){ for(int j=0;j<i;j++) if(a[j]>a[j+1]){ int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } void advanced_bubble_sort(int *a,int len){//优化的起泡排序 int high=len; while(high>0){ int last_changed=0; for(int j=0;j<len;j++) if(a[j]>a[j+1]){ int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; last_changed=j; } high=last_changed; } } void heap_rebuild(int * a,int low=1,int high=9){//堆排序中重建大根堆 int temp=a[low]; for(int j=2*low;j<=high;j*=2){ if(a[j+1]>a[j]&&j<high) j++; if(temp>=a[j]) break; a[low]=a[j]; low=j; } a[low]=temp; } void heap_sort(int * a,int low=1,int high=9){//堆排序过程; for(int i=low+(high-low)/2;i>=low;i--) heap_rebuild(a,i,high); for(int j=high;j>low;j--){ int temp=a[j]; a[j]=a[low]; a[low]=temp; heap_rebuild(a,low,j-1); } } void main(int argc, char* argv[]) { int a[]={0,1,2,3,4,5,6,7,8,9}; //partition1(a,0,9); //quick_sort(a,0,9); //bubble_sort(a,10); //advanced_bubble_sort(a,10); heap_sort(a,1,9); //quick_sort1(a,0,9); for(int i=0;i<10;i++) cout<<a[i]<<" "; }