zoukankan      html  css  js  c++  java
  • 算法导论 第二章 简单排序算法--插入排序,冒泡排序,选择排序

    插入排序

    /*
     * Insertion_sort time complexity:
     * Best-case: if the original sequence is sorted in a wanted-order: O(n)
     * Worst-case: if the original array is sorted in a reverse order: O(n^2)
     */
    void insertion_sort(int a[], int n)
    {
        int i, j, key;
        for (j = 1; j < n; ++j) {
            key = a[j];
            i = j - 1;
            while (i >= 0 && a[i] > key) {
                a[i+1] = a[i];
                --i;
            }
            a[i+1] = key;
        }

    }


    冒泡排序

    /*
     * 算法复杂度 O(n^2)
     */
    void BubbleSort(int a[], int n)
    {
        int i, j, temp;
        //int flag = 0;
     
        for (i = 0; i < n; ++i) {
            //flag = 0;
            for (j = n-1; j > i; --j) {
                if (a[j] < a[j-1]) {
                    //flag = 1;
                    temp = a[j];
                    a[j] = a[j-1];
                    a[j-1] = temp;
                }
            }
           // if (flag == 0)
           //     break;
        }
    }


    选择排序:

    /*
     * Selection_sort(A)
     * First find the smallest element of A and exchang it with A[1],
     * then find the second smallest element of A and exchang it with A[2]
     * continue this manner for the first n-1 elements of A.
     * Runnig time:
     * O(n^2) both in the Best and Worst-case.
     */
    int find_min(int a[], int start, int end)
    {
        int i;
        int res = start;
        for (i = start+1; i < end; ++i)
            if (a[res] > a[i])
                res = i;
        return res;
    }
     
    void selection_sort(int a[], int n)
    {
        int j, k;
        int temp;
        for (j = 0; j < n-1; ++j) {
            k = j;
            k = find_min(a, j, n);
            if (k != j) {   // if a[j] is already the smallest we don't do this
                temp = a[k];
                a[k] = a[j];
                a[j] = temp;
            }
        }
    }

  • 相关阅读:
    C++ 函数指针
    windows重建ESP分区修复引导
    [Python] typora文档复制到博客图片失效 SM.MS限制
    [Python] 破解一款软件验证
    requests.packages.urllib3.exceptions.ProxySchemeUnknown: Not supported proxy scheme
    nvalidSchema: Missing dependencies for SOCKS support
    html 未选择复选框不上传
    deepin linux 安装之后 引导错误 出现 grub>
    js/jquery加入的select value显示不正确问题
    请求响应状态status为canceled
  • 原文地址:https://www.cnblogs.com/huiqin/p/3674859.html
Copyright © 2011-2022 走看看