• 冒泡排序、插入排序和归并排序代码


    冒泡排序

    procedure bubbleSort(A[1-n])

    Begin

       for i=1 to n-1

            for j=n down to i+1 do

                  if A[j-1]>A[j] then

                  begin

                       temp=A[j-1]

                       A[j-1]=A[j]

                       A[j]=temp

             end

      end

    插入排序

    void insertion_sort(void) 

        int i, j, key;

        for (j = 1; j < LEN; j++) {

                key = a[j]; 

                i = j - 1; 

                while (i >= 0 && a[i] > key) {

                              a[i+1] = a[i]; 

                                i--; 

                 }

               a[i+1] = key; 

         }

    }

    归并排序

    #include <stdio.h>

    #define LEN 8

    int a[LEN] = { 5, 2, 4, 7, 1, 3, 2, 6 };

    void merge(int start, int mid, int end)

    {

             int n1 = mid - start + 1;

             int n2 = end - mid;

             int left[n1],

             right[n2];

             int i, j, k;

             for (i = 0; i < n1; i++) /* left holds a[start..mid] */

                           left[i] = a[start+i];

             for (j = 0; j < n2; j++) /* right holds a[mid+1..end] */

                           right[j] = a[mid+1+j];

             i = j = 0;

             k = start;

             while (i < n1 && j < n2) {

                      if (left[i] < right[j])

                             a[k++] = left[i++];

                      else

                              a[k++] = right[j++];

              }

             while (i < n1) /* left[] is not exhausted */

                     a[k++] = left[i++];

             while (j < n2) /* right[] is not exhausted */

                    a[k++] = right[j++];

    }

    void sort(int start, int end)

    {

            int mid;

            if (start < end) {

                      mid = (start + end) / 2;

                      printf("sort (%d-%d, %d-%d) %d %d %d %d %d %d %d %d ",

                                  start, mid, mid+1, end, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);

                      sort(start, mid);

                      sort(mid+1, end); merge(start, mid, end);

                      printf("merge (%d-%d, %d-%d) to %d %d %d %d %d %d %d %d ",

                                 start, mid, mid+1, end, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);

             }

    }

    int main(void){

             sort(0, LEN-1);

             return 0;

    }

  • 相关阅读:
    wamp+phpzendstudio配置xdebug57%解决办法
    【linux学习问题解决】使用aptget安装软件出现unable to locate package的解决办法
    【linux LAMP平台安装】写在前面(一)
    【linux学习问题解决】更改字符界面大小(转)
    [phpcms二次开发]phpcms生成栏目出错,转到模版页面
    [phpcms二次开发]给url规则添加可用更多自定义可用变量
    [phpcms二次开发]实现获取路径linux与windows路径兼容
    控件注册 利用资源文件将dll、ocx打包进exe文件(转)
    C#串口通信:MSComm控件使用详解
    改善C#程序的建议1:非用ICloneable不可的理由
  • 原文地址:https://www.cnblogs.com/startover/p/3141669.html
Copyright © 2020-2023  润新知