查看: 20326| 回复: 36
跳转到指定楼层
上一主题 下一主题
收起左侧

Stanford Design and Analysis of Algorithm I 第二期 Week#2 自由讨论

 关闭
全局:
Topics:
Part IV -- the Master Method. These lectures cover a "black-box" method for solving recurrences. It allows you to immediately determine the running time of most of the divide-and-conquer algorithms that you'll ever see! (Including Karatsuba's integer multiplication algorithm and Strassen's matrix multiplication algorithm from Week 1.) The proof is a nice generalization of the recursion tree method that we used to analyze MergeSort. Ever wonder about the mysterious three cases of the Master Method? Watch these videos and hopefully all will become clear.

Part V -- QuickSort (Algorithm). One of the greatest algorithms ever, and our first example of a randomized algorithm. These lectures go over the pseudocode --- the high-level approach, how to partition an array around a pivot element in linear time with minimal extra storage, and the ramifications of different pivot choices --- and explain how the algorithm works.

Part VI -- QuickSort (Analysis). These lectures are optional, but I strongly encourage you to watch them if you have time. They prove that randomized QuickSort (i.e., with random pivot choices) runs in O(n log n) time on average, with small constants. The analysis is as elegant as the algorithm itself, and is based on a "decomposition principle" that is often useful in the analysis of randomized algorithms. Note that there are some accompanying lectures notes for this part; the icon for downloading them is right next to the PDF slides for these lectures.

Part VII -- Probability Review. This optional lecture reviews the concepts from discrete probability that are necessary for the QuickSort analysis --- sample spaces, events, random variables, expectation, and linearity of expectation.


Homework:
Problem Set #2 has five questions that should give you practice with the Master Method and help you understand QuickSort more deeply.

Programming Assignment #2 asks you to implement QuickSort and compute the number of comparisons that it makes for three different pivot rules. The due dates are the same as for the problem set; here, 5 attempts are permitted.
单选投票, 共有 50 人参与投票
98.00% (49)
2.00% (1)
您所在的用户组没有投票权限

上一篇:[Coursera]Stanford 算法课 Design and Analysis of Algorithm I 第二期 Week1 加分贴
下一篇:Udacity 今天也有一门算法课出来,应该比stanford的简单不少
🔗
sevensin 2012-6-20 02:25:18 | 只看该作者
全局:
本帖最后由 sevensin 于 2012-6-20 12:38 编辑

关于quickSort,有几种实现,这本书<<Beautiful Code: Leading Programmers Explain How They Think>> 第三章讲得很好,老师也是用的这个方法。wikibook上面还讲了一种方法,有空可以自娱自乐一下。没有什么新的,除了数组操作下标,依旧很重要。要么多尝试,要么就在纸上好好想清楚。

代码如下,不知道最后数字对不对。但是至少排序没有问题。

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;


bool checkSort(vector<int> &a) {        // Check whether array is increasing
        for (int k = 0; k < (int) a.size() - 1; k++) {
                if (a[k] > a[k + 1])
                        return false;
        }
        return true;
}


void quickSort1(vector<int> &a, int l, int r, long long &comps) {
        if (l >= r)
                return;
        int idxp = l, i = l, temp;
        for (int j = l + 1; j <= r; j++) {
                if (a[j] < a[idxp]) {
                        ++i;
                        temp = a[j];
                        a[j] = a;
                        a[i] = temp;

                }
        }
        temp = a[l];
        a[l] = a[i];

        a[i] = temp;

        comps += r - l;
        quickSort1(a, l, i - 1, comps);
        quickSort1(a, i + 1, r, comps);
}


void quickSort2(vector<int> &a, int l, int r, long long &comps) {
        if (l >= r)
                return;
        int temp = a[r];
        a[r] = a[l];
        a[l] = temp;
        int idxp = l, i = l;
        for (int j = l + 1; j <= r; j++) {
                if (a[j] < a[idxp]) {
                        ++i;
                        temp = a[j];
                        a[j] = a[i];

                        a[i] = temp;

                }
        }
        temp = a[l];
        a[l] = a[i];

        a[i] = temp;

        comps += r - l;
        quickSort2(a, l, i - 1, comps);
        quickSort2(a, i + 1, r, comps);
}


void quickSort3(vector<int> &a, int l, int r, long long &comps) {
        if (l >= r)
                return;
        int pivot = (l + r) / 2;
        if ((a[l] < a[pivot] && a[l] > a[r]) || (a[l] > a[pivot] && a[l] < a[r]))
                pivot = l;
        if ((a[r] < a[pivot] && a[r] > a[l]) || (a[r] > a[pivot] && a[r] < a[l]))
                pivot = r;
        int temp = a[pivot];
        a[pivot] = a[l];
        a[l] = temp;
        int idxp = l, i = l;
        for (int j = l + 1; j <= r; j++) {
                if (a[j] < a[idxp]) {
                        ++i;
                        temp = a[j];
                        a[j] = a[i];

                        a[i] = temp;

                }
        }
        temp = a[l];
        a[l] = a[i];

        a[i] = temp;

        comps = comps + r - l;
        quickSort3(a, l, i - 1, comps);
        quickSort3(a, i + 1, r, comps);
}


int main() {
        string InputFileName = "QuickSort.txt";
        ifstream infile(InputFileName.c_str());
        if (!infile.is_open()) {
                cerr << "Error with file opening: "<<InputFileName<<endl;
                exit(1);
        }
        vector<int> IntArray, NewArray1, NewArray2, NewArray3;
        string templine;
        while (!infile.eof()) {
                getline(infile, templine);
                if (templine.size() == 0)
                        continue;
                IntArray.push_back(std::atoi(templine.c_str()));
        }
        infile.close();
        cout << IntArray.size() << " numbers acquired." << endl;
        NewArray1 = IntArray;
        NewArray2 = IntArray;
        NewArray3 = IntArray;
        long long comps1 = 0, comps2 = 0, comps3 = 0;
        quickSort1(NewArray1, 0, NewArray1.size() - 1, comps1);
        quickSort2(NewArray2, 0, NewArray2.size() - 1, comps2);
        quickSort3(NewArray3, 0, NewArray3.size() - 1, comps3);
        if (!checkSort(NewArray1)) {
                cerr << "Wrong with this quickSort1";
        }
        if (!checkSort(NewArray2)) {
                cerr << "Wrong with this quickSort2";
        }
        if (!checkSort(NewArray3)) {
                cerr << "Wrong with this quickSort3";
        }
        cout << "# of comparisons in Problem 1:\t" << comps1 << endl;
        cout << "# of comparisons in Problem 2:\t" << comps2 << endl;
        cout << "# of comparisons in Problem 3:\t" << comps3 << endl;
        return 0;
}



# of comparisons in Problem 1:        162085
# of comparisons in Problem 2:        164123
# of comparisons in Problem 3:        138382

[/i][/i][/i][/i][/i][/i][/i][/i][/i][/i][/i]

评分

参与人数 1大米 +20 收起 理由
paradox + 20 感谢分享!

查看全部评分

回复

使用道具 举报

🔗
sevensin 2012-6-20 12:41:34 | 只看该作者
全局:
再上Python。相比week1的作业,这次 python版本和C++区别不大,唯一就是swap方便一点。基本思路完全一样,只有具体实现不同罢了。
import random
def qSort(a,l,h,comp):
        if l>=h: return a, comp
        #pivot = l  # Problem 1
        #pivot = h  # Problem 2
        #pivot = random.randint(l,h)  # using random pivot, it sucks...
        pivot = (l+h)/2 # Problem 3
        if ((a[l]<a[pivot] and a[l]>a[h]) or (a[l]>a[pivot] and a[l]<a[h])): pivot = l
        if ((a[h]<a[pivot] and a[h]>a[l]) or (a[h]>a[pivot] and a[h]<a[l])): pivot = h
        a[pivot], a[l] = a[l], a[pivot]
        i=l
        for j in range(l+1,h+1,1):
                if a[j]<a[l]:
                        i=i+1
                        a[i],a[j]=a[j],a[i]
        a[l],a[i]=a[i],a[l]
        comp=comp+h-l
        a,comp=qSort(a,l,i-1,comp)
        a,comp=qSort(a,i+1,h,comp)
        return a,comp
       
def non_decreasing(L):
    return all(x<=y for x, y in zip(L, L[1:]))


InputFileName = "QuickSort.txt"
FileIn = open(InputFileName, 'r')
IntArray = map(int, FileIn.readlines())
FileIn.close()
print "Read " + str(len(IntArray)) + " integers from file: " + InputFileName
comps=0
(res, comps)=qSort(IntArray,0,len(IntArray)-1,comps)
print "The # of comparison is \t %d" %(comps)
if not non_decreasing(res):
        print "Incorrect sorted result"


回复

使用道具 举报

🔗
DWade 2012-6-20 18:17:13 | 只看该作者
全局:
Feedback — Problem Set-2
You achieved a score of 8.00 out of 8.00
Question 1
This question will give you further practice with the Master Method. Suppose the running time of an algorithm is governed by the recurrence T(n)=7∗T(n/3)+n2. What's the overall asymptotic running time (i.e., the value of T(n))? Note: If you take this quiz multiple times, you may see different variations of this question.
Your Answer                Score        Explanation
θ(n2)                1.00        a=7, b=3, d=2. Since b^d > a, this is case 2 of the Master Method.
Total                1.00 / 1.00       
Question 2
Consider the following pseudocode for calculating ab (where a and b are positive integers)

      FastPower(a,b) :

              if b = 1

                   return a

              otherwise

                   c := a*a

                   ans := FastPower(c,[b/2])

               if b is odd

                   return a*ans

               otherwise return ans

end


Here [x] denotes the floor function, that is, the largest integer less than or equal to x.
Now assuming that you use a calculator that supports multiplication and division (i.e., you can do multiplications and divisions in constant time), what would be the overall running time of the above algorithm (as a function of b)?
Your Answer                Score        Explanation
log(b)                2.00        Constant work per digit in the binary expansion of b.
Total                2.00 / 2.00       
This gives you a nice way of raising a number to the power in multiplications much less than b. You can get the answer by looking at the binary expression for b.
Question 3
Let 0<α<.5 be some constant. Recall the Partition subroutine employed by the QuickSort algorithm, as explained in lecture. What is the probability that, with a randomly chosen pivot element, the Partition subroutine produces a split in which the size of the smaller of the two subarrays is ≥α times the size of the original array?
Your Answer                Score        Explanation
1−2∗α                2.00       
Total                2.00 / 2.00       
Question 4
Now assume that you achieve the approximately balanced splits above in every recursive call --- that is, every recursive call is passed a subarray that contains between an α and 1−α fraction of the elements of the given array (for some constant 0<α<.5). What is the order of depth d in the recursive tree (i.e., the range of the number of successive recursive calls before hitting the base case)?
Your Answer                Score        Explanation
−log(n)log(α)≤d≤−log(n)log(1−α)                2.00       
Total                2.00 / 2.00       
Recall the recursion tree method taught in MergeSort and Master Method lectures.
Question 5
Define the recursion depth of QuickSort to be the maximum number of successive recursive calls before it hits the base case --- equivalently, the number of the last level of the corresponding recursion tree. Note that the recursion depth is a random variable, which depends on which pivots get chosen. What is the recursion depth of QuickSort (both for a best-case choice of pivots, and for a worst-case choice of pivots)?
Your Answer                Score        Explanation
Best: log(n) ; worst: n                1.00        The best case is when the algorithm always picks the median as a pivot, in which case the recursion is essentially identical to that in MergeSort. In the worst case the min or the max is always chosen as the pivot, resulting in linear depth.
Total                1.00 / 1.00       
回复

使用道具 举报

🔗
DWade 2012-6-21 11:08:12 | 只看该作者
全局:
下面贴编程问题 只贴第一题 因为后面的类似
  1. public static int sort(int[] a, int low, int high){
  2.                 if(high<=low){return 0;}
  3.                 else{
  4.                         int pivot=a[low];
  5.                         int split=low;
  6.                         for(int i=low+1;i<=high;i++){
  7.                                 if(a[i]<=pivot){
  8.                                         int temp= a[split+1];
  9.                                         a[split+1]= a[i];
  10.                                         a[i] =temp;
  11.                                         split++;
  12.                                 }
  13.                         }
  14.                         int temp= a[low];
  15.                         a[low] =a[split];
  16.                         a[split]=temp;
  17.                         int y= sort(a,low,split-1);
  18.                         int z= sort(a,split+1,high);
  19.                         return y+z+high-low;
  20.                 }
  21.         }
复制代码
回复

使用道具 举报

🔗
DWade 2012-6-21 11:13:36 | 只看该作者
全局:
算了 还是把第二题的也贴出来吧 。就是加了三排交换a[high]和a[low]的代码
  1. public static int sort(int[] a, int low, int high){
  2.                 if(high<=low){return 0;}
  3.                 else{
  4.                         int temp1= a[low];
  5.                         a[low] =a[high];
  6.                         a[high]=temp1;
  7.                         int pivot=a[low];
  8.                         int split=low;
  9.                         for(int i=low+1;i<=high;i++){
  10.                                 if(a[i]<=pivot){
  11.                                         int temp= a[split+1];
  12.                                         a[split+1]= a[i];
  13.                                         a[i] =temp;
  14.                                         split++;
  15.                                 }
  16.                         }
  17.                         int temp= a[low];
  18.                         a[low] =a[split];
  19.                         a[split]=temp;
  20.                         int y= sort(a,low,split-1);
  21.                         int z= sort(a,split+1,high);
  22.                         return y+z+high-low;
  23.                 }
  24.         }
复制代码
回复

使用道具 举报

🔗
justin 2012-6-21 16:05:06 | 只看该作者
全局:
本帖最后由 justin 于 2012-6-21 16:06 编辑

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#define N 10000
using namespace std;

long long int cp = 0;

void Partition_first(vector<int> A, int l, int r)
{
    //cout << l << " " << r << endl;
    //if(l == r) return;
    cp += r - l;
    int p = A[l];
    int i = l + 1, j = l + 1;
    for(; j <= r; j++)
    {
        if(A[j] < p)
        {
            swap(A[j], A);
            i++;
        }
    }
    swap(A[l], A[i-1]);
    if(i - 2 > l)
        Partition_first(A, l, i-2);
    if(i < r)
        Partition_first(A, i, r);
}

void Partition_last(vector<int> A, int l, int r)
{
    swap(A[l], A[r]);
        //cout << l << " " << r << endl;
    //if(l == r) return;
    cp += r - l;
    int p = A[l];
    int i = l + 1, j = l + 1;
    for(; j <= r; j++)
    {
        if(A[j] < p)
        {
            swap(A[j], A);
            i++;
        }
    }
    swap(A[l], A[i-1]);
    if(i - 2 > l)
        Partition_last(A, l, i-2);
    if(i < r)
        Partition_last(A, i, r);
}

void Partition_median(vector<int> A, int l, int r)
{
    int m = (l + r) / 2;
    if((A[l] > A[m] && A[m] > A[r]) || (A[r] > A[m] && A[m] > A[l]))
        swap(A[l], A[m]);
    else if((A[l] > A[r] && A[r] > A[m]) || (A[m] > A[r] && A[r] > A[l]))
        swap(A[l], A[r]);
        //cout << l << " " << r << endl;
    //if(l == r) return;
    cp += r - l;
    int p = A[l];
    int i = l + 1, j = l + 1;
    for(; j <= r; j++)
    {
        if(A[j] < p)
        {
            swap(A[j], A);
            i++;
        }
    }
    swap(A[l], A[i-1]);
    if(i - 2 > l)
        Partition_median(A, l, i-2);
    if(i < r)
        Partition_median(A, i, r);

}

int main()
{
    vector<int> A;
    ifstream fin("QuickSort.txt");
    string num;
    fin >> num;
    while(!fin.eof())
    {
        A.push_back(atoi(num.c_str()));
        fin >> num;
    }
    vector<int> B(A);
    vector<int> C(A);

    cp = 0;
    Partition_first(A, 0, N-1);
    cout << "choosing the first element as pivot: " << cp << endl;

    cp = 0;
    Partition_last(A, 0, N-1);
    cout << "choosing the last element as pivot: " << cp << endl;

    cp = 0;
    Partition_median(A, 0, N-1);
    cout << "choosing the median element as pivot: " << cp << endl;

    cout << "Hello world!" << endl;
    return 0;
}


贴个代码(突然发现helloworld那行还留着……呵呵)
发现老外教的quicksort和严蔚敏版的数据结构上写的不一样,求大神比较下这两种实现方式有什么区别,有什么优劣?


回复

使用道具 举报

🔗
justin 2012-6-21 16:07:27 | 只看该作者
全局:

贴个代码(突然发现helloworld那行还留着……呵呵)
发现老外教的quicksort和严蔚敏版的数据结构上写的不一样,求大神比较下这两种实现方式有什么区别,有什么优劣?

PS:为什么回复内容只能以一种字体格式显示?
回复

使用道具 举报

🔗
seekinghelp 2012-6-22 21:22:12 | 只看该作者
全局:
本帖最后由 seekinghelp 于 2012-6-22 21:23 编辑

贴一下Problem Set-2的Question 1吧,因为这个每个人都不一样:This question will give you further practice with the Master Method. Suppose the running time of an algorithm is governed by the recurrence T(n)=9∗T(n/3)+n2. What's the overall asymptotic running time (i.e., the value of T(n))? Note: If you take this quiz multiple times, you may see different variations of this question.
Your Answer

Score
Explanation
θ(n2logn)
1.00
a = b^d = 9, so this is case 1 of the Master Method.
Total

1.00 / 1.00




回复

使用道具 举报

🔗
EDream 2012-6-23 10:52:16 | 只看该作者
全局:
本帖最后由 EDream 于 2012-6-23 16:45 编辑

前阵子忙着毕业,昨天把lecture都看了,先贴出Programming Question的Code。有个疑问,在Java里面参数的传递方式貌似是被限定死的,primitive type只能以hard copy的形式传递,这就导致计数的时候只能计数的时候无法track到内层的recursion。我能想到的只是简单地做一个数组进行传递,因为数组默认是pass by reference的。如果依旧想用int进行传递,大家有其它的方法吗?


package Edream_QuickSort;
import java.io.*;
public class QS {        
        public static String PATH = "QuickSort.txt";
        public static int ARR_LEN = 10000;
        
        public static void main(String args[]) {
                int [] num_arr = new int[ARR_LEN];
                int[] numCp1 = new int[1];
                int[] numCp2 = new int[1];
                int[] numCp3 = new int[1];
                BufferedReader rd = OpenFileReader();
                ReadFile(rd, num_arr);
               
                numCp1= QuickSort1(num_arr, 0, num_arr.length-1, numCp1);
                numCp2= QuickSort2(num_arr, 0, num_arr.length-1, numCp2);
                numCp3= QuickSort3(num_arr, 0, num_arr.length-1, numCp3);
               
                System.out.println("No. of comparisons using first elem as pivot is: ");
                System.out.println(numCp1[0]);
                System.out.println("No. of comparisons using last elem as pivot is: ");
                System.out.println(numCp2[0]);
                System.out.println("No. of comparisons using median-three elem as pivot is: ");
                System.out.println(numCp3[0]);
        }
        
        public static BufferedReader OpenFileReader() {
                BufferedReader rd = null;
                try {
                        while (rd == null) {
                                rd = new BufferedReader(new FileReader(PATH));
                        }
                } catch (IOException ex) {
                        System.out.println("Cannot open that file!");
                }
                return rd;
        }
        
        public static void ReadFile(BufferedReader rd, int[] num_arr) {
                try {
                        int index = 0;
                        while (true) {
                                String num = rd.readLine();
                                if (num == null) break;
                                num_arr[index++] = Integer.parseInt(num);
                        }
                } catch (IOException ex) {
                        System.out.println("An I/O Error occurred.");
                }
        }
        
        public static int[] QuickSort1(int[] arr, int l, int r, int[] numCp) {
                if (l >= r)
                        return numCp;
               
                int i = l + 1, j = l + 1;
                int pivot = l;
                for (; j < arr.length; j++) {
                        if (arr[j] < arr[pivot]) {
                                swap(arr, i, j);
                                i++;
                        }
                }
                swap(arr, pivot, i - 1);
                numCp[0] += r - l;
                QuickSort1(arr, l, i - 2, numCp);
                QuickSort1(arr, i, r, numCp);
               
                return numCp;
        }
        
        public static int[] QuickSort2(int[] arr, int l, int r, int[] numCp) {
                if (l >= r)
                        return numCp;
               
                int i = l + 1, j = l + 1;
                swap(arr, l, r);
                int pivot = l;
                for (; j < arr.length; j++) {
                        if (arr[j] < arr[pivot]) {
                                swap(arr, i, j);
                                i++;
                        }
                }
                swap(arr, pivot, i - 1);
                numCp[0] += r - l;
                QuickSort2(arr, l, i - 2, numCp);
                QuickSort2(arr, i, r, numCp);
               
                return numCp;
        }
        
        public static int[] QuickSort3(int[] arr, int l, int r, int[] numCp) {
                if (l >= r)
                        return numCp;
               
                int pIdx = (l + r) / 2;
                if (arr[l] > arr[pIdx] && arr[l] < arr[r] || arr[l] > arr[r] && arr[l] < arr[pIdx])
                        pIdx = l;
                if (arr[r] > arr[pIdx] && arr[r] < arr[l] || arr[r] > arr[l] && arr[r] < arr[pIdx])
                        pIdx = r;
                swap(arr, pIdx, l);
               
                int i = l + 1, j = l + 1;
                int pivot = l;
                for (; j < arr.length; j++) {
                        if (arr[j] < arr[pivot]) {
                                swap(arr, i, j);
                                i++;
                        }
                }
                swap(arr, pivot, i - 1);
                numCp[0] += r - l;
                QuickSort3(arr, l, i - 2, numCp);
                QuickSort3(arr, i, r, numCp);
               
                return numCp;
        }
        
        public static void swap(int[] arr, int i, int j) {
                int temp = arr;
                arr[i] = arr[j];

                arr[j] = temp;
        }
}
[/i]

最后再提一下problem sets的两道题,try了好多次才做对...

Question3读了好几遍才理解题意,是要求出最小subarray size >=an的概率
1) pivot -> (0, an), not exist
2) pivot -> (an, (1-a)n), (1-a)n > an, meet the req
3) pivot -> ((1-a)n, n), not exist, same as 1)
Question4求两个depth极值

since 0< a < 0.5 => 1-a > a
smallest order is log(1/N)/log(a)
biggest order is log(1/N)/log(1-a)


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表