zoukankan      html  css  js  c++  java
  • 排序算法

    堆排:

    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>

    using namespace std;

    void heapadjust(int a[],int len,int i)
    {
     int t=a[i];
     bool flag=true;
     int j=2*i;
     while(flag && j<=len)  // 注意要有等于号
     {
      if((j+1)<=len && a[j+1]>a[j])
       j++;
      if(t>=a[j])
       flag=false;
      else
      {
       a[i]=a[j];    //注意这三个语句的顺序
       i=j;
       j=2*i;   
      }
      
     }
     a[i]=t;
    }

    void heapcreate(int a[],int len)
    {
     for(int i=len/2;i>0;i--)
     {
      heapadjust(a,len,i);
     }

    }

    void heapsort(int a[],int len)
    {
        int e;
     heapcreate(a,len);     //注意这是创建堆,而非调整堆
     for(int i=len;i>=1;i--)
     {
      cout<<a[1]<<" ";
      e=a[1];
      a[1]=a[i];
      a[i]=e;
      heapadjust(a,i-1,1);  // 这里是i-1,而不是len-1
     }
     cout<<endl;
    }

    void print(int a[],int len)
    {
     for(int i=0;i<=len;i++)
      cout<<a[i]<<" ";
     cout<<endl;
    }

    int main()
    {
     int a[]={0,12,3,4,2,5,9,7,23,6,8};
     int len=10;
     print(a,10);
     heapsort(a,10);
     print(a,10);
     return 0;
     
    }

     快速排序

    #include <iostream>
    #include <stdlib.h>
    #include <stdio.h>

    using namespace std;

    void quicksort(int a[],int low,int high)
    {

    if(low<high)    // 注意这儿必须要有

    {
     int base=a[low];
     int pos=low;
     int pos1=high;
     while(low<high)
     {
      while(low<high && a[high]>=base)
       high--;
      if(low<high)
      {   
       a[low]=a[high];       // 注意这里不是a[high]=a[low]
       low++;
      }

      while(low<high && a[low]<=base)
       low++;
      if(low<high)
      {
       a[high]=a[low];
       high--;
      }
      
     }
       a[low]=base;
      // cout<<a[low]<<endl;
       quicksort(a,pos,low-1);
       quicksort(a,low+1,pos1);

    }
    }

    void print(int a[],int len)
    {
     for(int i=0;i<len;i++)
      cout<<a[i]<<" ";
     cout<<endl;
    }
    int main()
    {
       int a[]={4,8,9, 6 , 7 , 3 , 1 , 10 , 2,5};
       int len=10;
       print(a,len);
       quicksort(a,0,len-1);
       print(a,len);
    }

  • 相关阅读:
    【转】wpa_supplicant与wpa_cli之间通信过程
    CSS Hack
    HTML5测试(二)
    HTML5测试(一)
    百分号编码(URL编码)
    DOM事件处理函数
    JS数组
    JS中for循环嵌套
    Codecombat 游戏攻略(计算机科学三)2
    Codecombat 游戏攻略(计算机科学三)
  • 原文地址:https://www.cnblogs.com/hualimengyu/p/3337720.html
Copyright © 2011-2022 走看看