zoukankan      html  css  js  c++  java
  • [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);
        }
    }
  • 相关阅读:
    Android-Java-构造方法内存图
    redis conf 详解
    redis windows 下安装及使用
    Python 学习笔记(一)
    python 配置
    win 7 下vim的使用
    window下安装Node.js NPM
    HashMap实现原理(转)
    mysql 常用功能
    MySql配置
  • 原文地址:https://www.cnblogs.com/otakuhan/p/8607281.html
Copyright © 2011-2022 走看看