The analysis of the time complexity of bucket sequencing and band Loop algorithm

Source: Internet
Author: User
Tags data structures readline sort in python

In calculating the time complexity of the algorithm, we generally adopt the Bigo function. The Bigo function retains only the most valuable function components, removing the coefficients and removing the constants. For example: O (a*n^2+b*n+1) =o (n^2). At the same time we try to choose the closest Bigo function when we analyze the algorithm. For example, the algorithm for fast Sorting (QuickSort) and merge (MergeSort) can be either O (n^2) or O (N*LGN), but we will choose O (N*LGN) because it is closest.

Simple algorithm, many times, through intuition we can draw its time complexity. For example, if you see the following statement, if dosomething time complexity is O (1), then the time complexity of the whole algorithm is O (n^2).

For I in range (n): for
    J in Range (n):
        doSomething2
When you see the following statement, the time complexity of the entire algorithm is O (n).

For I in range (n):
    doSthing1

But sometimes intuition is wrong, such as the bucket sorting algorithm, which has a double loop, but the time complexity of the algorithm is actually linear. Before we study the bucket sorting algorithm in detail, we need to first understand how to analyze the time complexity of the while (or for) loop. For example, the following algorithm:

While S1:
    S2
S1 and S2 can be compound statements with a time complexity other than O (1). If the number of executions of this loop is N, then the S2 statement executes n times, and the S1 statement executes n+1 times. (For loop same), the time complexity of the whole algorithm is O (s1* (n+1)) or O (s2*n), whichever is the maximum. For simple Algorithms s1* (n+1) is meaningless, such as the following algorithm, time complexity O (n+1) =o (n). But in complex algorithms, such as the bucket sorting algorithm, the constant 1 in O (n+1) has meaning.

For I in range (n):
    i+1

The following is the bucket sorting algorithm. First of all intuitively, the 12th and 13 lines are double loops, the number of external heavy cycles m, the internal heavy loop BUCKETS[J] Maximum value may be n, then the time complexity of the algorithm is O (m*n), but actually it is not the closest Bigo function. Let's examine it in detail. Because there are only n elements in total, the 14th row is actually executed only n times. Looking at 13 rows, the inner loop executes (buckets[j]+1) times, The outer loop executes m times, then the entire 12 and 13 rows are executed (buckets[0]+1) + (buckets[1]+1) +...+ (buckets[m-1]+1) =n+m. So the time complexity of the whole algorithm is O (m+n), rather than the intuitive O (m*n).

Geneva 
Import Random 
bucketsort (alist, N, buckets, m): For me in     range (m):         Buckets[i]=0
to     i in range (n):         buckets[alist[i]] + = 1     i=0
(     J) in range (m):        
+         -K in range (Buckets[j]):             alist[i]=j             i+=1 
If __name__ = = ' __main__ ':     m=10     n=40     alist=[ Random.randrange (0,m) for I in range (n)]     buckets=[0] *     print (' before sort ')
23     print (alist)     bucketsort (alist,n,buckets,m)     print (' after sort ')     Print (alist) 
28 

The following is the output of the bucket sorting algorithm once executed. Bucket sorting is only suitable for certain types of sorting.

Before sort
[7, 1, 6, 4, 6, 0, 2, 9, 3, 9, 6, 3, 9, 1, 5, 1, 1, 6, 0, 8, 2, 0, 1, 0, 7, 9, 1, 5, 7, 8, 7, 4, 7, 0, 0, 7, 8, 8, 9, 3] after
sort
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9]



Reference documents:

Data structures and algorithms with object-oriented Design Patterns in Python

P.S. The body part to this end, the preceding Python program line number is generated by the following program, is a program I wrote before, leaving a souvenir.

Import java.util.*;

Import java.io.*; public class number{public static void Main (string[] args) throws exception{long Start=system.currenttimemi
        Llis ();
        System.out.println ("Start time:" +start);
            if (args.length!=2) {System.out.println ("Usage:java number <infile> <outFile>");
        Return
        } BufferedReader Inreader = new BufferedReader (new FileReader (Args[0]));
        BufferedWriter outwriter = new BufferedWriter (new FileWriter (args[1]));
        int count=0;
        String Line=null;
            do{line = Inreader.readline ();
            if (line!=null) {count++;
            } else{break;

        }} while (true);
            if (count<=0) {System.out.println (Args[0] + "have zero line");
        Return
        } String strcount=integer.tostring (count); System.out.println ("strcount=" +strcount);
        int width = strcount.length ();
        System.out.println ("width=" +width);
        Inreader.close ();
        count=0;
        Inreader = new BufferedReader (new FileReader (args[0));
            do{line = Inreader.readline ();
                if (line!=null) {count++;
                line = Addleadingzero (integer.tostring (count), width) + "" +line;
                Outwriter.write (Line,0,line.length ());
            Outwriter.newline ();
            } else{break;

        }} while (true);
        Inreader.close ();
        Outwriter.close ();
        Long End=system.currenttimemillis ();
        System.out.println ("End Time:" +end);
    SYSTEM.OUT.PRINTLN ("Total Second:" + (End-start)/1000);
        public static string Addleadingzero (string str,int width) {int len = str.length ();
        if (len>=width) return str;
        width = Width-len;
StringBuilder b=new StringBuilder (str);        for (; width>0;width--) {b.insert (0, ' 0 ');
    } return b.tostring ();
 }
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.