• [LintCode笔记了解一下]80.Median


    Given a unsorted array with integers, find the median of it.

    A median is the middle number of the array after it is sorted.

    If there are even numbers in the array, return the N/2-th number after sorted.

    思路:

    找个sort方法sort完后即可

    最简单的就是bubble sort

    但是bubble sort时间复杂度太大,所以改用quicksort

    /* This function takes last element as pivot, places
       the pivot element at its correct position in sorted
        array, and places all smaller (smaller than pivot)
       to left of pivot and all greater elements to right
       of pivot */
    int partition (int arr[], int low, int high)
    {
        int pivot = arr[high];    // pivot
        int i = (low - 1);  // Index of smaller element
     
        for (int j = low; j <= high- 1; j++)
        {
            // If current element is smaller than or
            // equal to pivot
            if (arr[j] <= pivot)
            {
                i++;    // increment index of smaller element
                swap(&arr[i], &arr[j]);
            }
        }
        swap(&arr[i + 1], &arr[high]);
        return (i + 1);
    }
     
    /* The main function that implements QuickSort
     arr[] --> Array to be sorted,
      low  --> Starting index,
      high  --> Ending index */
    void quickSort(int arr[], int low, int high)
    {
        if (low < high)
        {
            /* pi is partitioning index, arr[p] is now
               at right place */
            int pi = partition(arr, low, high);
     
            // Separately sort elements before
            // partition and after partition
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }
  • 相关阅读:
    从SQL注入谈数据访问层
    Combobox下拉框两级联动
    C#IO流文件操作
    网络电视精灵思路分析
    简单工厂和单例设计模式浅解
    可扩展标记语言
    深入理解多态
    未将对象引用到实例
    Python 项目实践二(生成数据)第一篇
    Python 项目实践一(外星人入侵小游戏)第五篇
  • 原文地址:https://www.cnblogs.com/otakuhan/p/8607281.html
Copyright © 2020-2023  润新知