几个排序和查找算法

    技术2022-05-11  52

     1.bubble_sort

    连续比较,若右边小于左边,则交换

    void bubble_sort(int array[],int size){ int i,j; for(i=0;i<size;i++)  for(j=i+1;j<size;j++)   if(array[j]<array[i])    swap(array[i],array[j]);}2.selection_sort

    每轮循环仅做一次交换,即每次比较仅记录序号,到最后再交换

    void selection_sort(int array[],int size){ int temp; bool flag=false; for(int i=0;i<size;i++) { temp=i;  for(int j=i+1;j<size;j++)  {   flag=false;   if(array[j]<array[temp])    temp=j;  }if(temp!=i){swap(array[temp],array[i]);  flag=true;}  if(!flag)  break; }}

    3.quick_sort

    每次选定一个种子,令左边小于它,右边大于它,然后依次递归

    void quick_sort(int array[],int first,int last){ int low,high,mid; low=first; high=last; mid=array[(first+last)/2]; do {  while(array[low]<mid)   low++;  while(array[high]>mid)   high--;  if(low<=high)   swap(array[low++],array[high--]);

     } while(low<=high); if(first<high)  quick_sort(array,first,high); if(low<last)  quick_sort(array,low,last);}

    4.binary_search

    int binary_search(int array[],int value,int size){ int found=0; int high=size,low=0,mid; mid=(low+high)/2; while((!found)&&(high>=low)) {  printf("Low %d Mid %d High %d/n",low,mid,high);  if(value==array[mid])   found=1;  else if(value<array[mid])   high=mid-1;  else   low=mid+1;  mid=(high+low)/2; } return (found)?mid:-1;}

    5.swap funtion

    void swap(int &a,int &b){ int temp; temp=a; a=b; b=temp;}


    最新回复(0)