• 算法导论 第二章 简单排序算法--插入排序,冒泡排序,选择排序


    插入排序

    /*
     * 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;
            }
        }
    }

  • 相关阅读:
    Memcached: 目录
    Memcached: temple
    Redis: Redis支持五种数据类型
    互联网市场
    java实现猜生日
    java实现汉诺塔计数
    java实现汉诺塔计数
    java实现汉诺塔计数
    java实现汉诺塔计数
    java实现汉诺塔计数
  • 原文地址:https://www.cnblogs.com/huiqin/p/3674859.html
Copyright © 2020-2023  润新知