Temporal / spatial complexity, based sorting algorithms (bubble, select, fast, insert)

First, the time complexity, space complexity

Time complexity: a thing used to evaluate the efficiency of the algorithm, with O () expressed

Examples time complexity calculation:

print ( ' Hello World ' )       O (1)
for I in Range (n-): #n cycles
      Print ( ' the Hello World ' )     O (n-)
for I in Range (n):
     for J in Range (n): n # two nested loops
         Print ( ' the Hello World ' )       O (N²)

The following code time complexity of it?

Print ( ' the Hello World ' )
 Print ( ' the Hello Python ' ) # is looking at three runs, but also O (1)
 Print ( 'the Hello Mathimatics-Numerical algorithms')         O (1)
for i in range(n):
    print('Hello World’)
        for j in range(n):
            print('Hello World')      O(n²)

The time complexity of the code following it?

the while n->. 1 :
     Print (n-) 
    n- = n-2 // 

2 ^ 64. 6 = 
Iog2 ^ = 64. 6 
so that the time complexity is: O (Iog2 ^ n-), can also be used as O (logn)

Time Complexity Summary:

1. The time complexity of the algorithm is used to estimate a running equation of time (units). 
2. In general, the time complexity of the algorithm is lower than the high complexity of the algorithm is slow.

How to judge a time complexity?

1. half cycle process: O (logn) 
complexity is 2 n times the cycle several side

Space complexity: a formula used to evaluate the algorithm memory footprint size.

Uses: space for time

Second, the list is sorted

Sort the list: The list of unordered list into order

Input: unordered list

Output: an ordered list

Several common sorting algorithms: bubble sort, selection sort, insertion sort, quick sort, etc.

1. Bubble Sort

Ideas:

1. Have an unordered list, Compare two adjacent numbers, if larger than behind the front, to exchange their two

2. For each doing the same work for neighbors, from the beginning to the end of the first to the last pair, so that the last element is the largest value.

3. Repeat the above steps, except the last one

So we write for two cycles:

The first for loop functions: controlling the number of rounds of sorting

The second for loop action: control of each round in each of the comparators

Bubble sort code is as follows:

li=[4,1,3,6,7,9,2,5,8]
def Bubble_sort(li):
    for i in range(len(li)-1):
        for j in range(len(li)-1-i):
            if li[j] > li[j+1]:
                li[j], li[j+1] = li[j+1], li[j]
    print(li)
Bubble_sort(li)   #排序结果 [1, 2, 3, 4, 5, 6, 7, 8, 9]

Bubble sort time complexity: O (n²), the spatial complexity is O (1)

Bubble sort optimization:

If the bubble sort is executed without a trip to the exchange, the list has been ordered state, it can be directly algorithm ends.

 

 

2. Select Sort 

Ideas:

1. trip traversing the smallest number of records, into the first position.

2. And then the minimum trip through the records of the number of remaining list, continue to place

Can be understood as: a list of index taking a value of 0, and a rear position of the element compared to the index value greater than the value 0 at other positions are swapped positions. And an index value of 0 over all the elements of the comparison, then the index value 1 and the following elements sequentially comparing a value of the index is greater than the value of the other positions are swapped positions, and so on, from small to large.

Select Sort Code Example:

li = [4,3,6,1,7,9,2,5,8 ] 

def select_sort (li):
     for i in range (len (li)): 
        minLoc = and    # ## = 0 
        for j , and range (i + 1 , len (li)):
             if the [j] < li [minLoc]: 
                li [j], the [minLoc] = the [minLoc], the [j]
     print (li) 
select_sort (li)    #结果[1, 2, 3, 4, 5, 6, 7, 8, 9]

Selection sort time complexity: O (n²), the spatial complexity is O (1)

3. Insertion Sort

Ideas: Similar Landlords inserted card

1. The list is divided into two parts ordered regions and disordered regions, only one element of the first ordered regions, extracting if the first element

2. Select one element from each of disorder, the ordered position of the insertion area, and eleven values ​​of ordered regions of the comparison until the disorder becomes empty area

Code sample insertion sort:

li=[4,3,6,1,7,9,2,5,8]
def insert_sort(li):
    for i in range(1, len(li)):
        tmp = li[i]
        j = i - 1
        while j >=0 and li[j] > tmp:
            li[j+1] = li[j]
            j = j - 1
        li[j+1] = tmp
    print(li)
insert_sort(li)   #结果  [1, 2, 3, 4, 5, 6, 7, 8, 9]

Insertion sort time complexity: O (n²), the spatial complexity is O (1)

4. Quick Sort

Sorting algorithm to write about in the fastest, the best fast sorting algorithm in writing (writing several more complex than before)

Ideas:

1. Remove the element from a column number (generally the first element), referred to as a "reference"

2. Write a function of the number reorder columns, all the elements are smaller than the reference benchmark on the left, all the elements are larger than the reference on the right, the same number to the same side. After the partition exit, on the basis of the number of columns in the middle position.

3. a write function, the recursive sub-elements than the reference value is greater than the number of columns and number of columns a sorting reference value of the element. The bottom case of recursion, the size is the number of columns is zero or one, that is, always has been sorted well. While it has been recursion, but this algorithm always quit, because in each iteration, it will at least one element placed in its final position to go.

Quick sort key points: 1 consolidation, 2 recursion.

 

 

 Quick sort code examples:

li=[4,3,6,1,7,9,2,5,8]
#第一个函数,根据基准分区
def partition(li, left, right):
    tmp = li[left]
    while left < right:
        while left < right and li[right] >= tmp:
            right = right - 1
        li[left] = li[right]
        while left < right and li[left] <= tmp:
            left = left + 1
        li[right] = li[left]
    li[left] = tmp

    return left
#第二个函数使用迭代
def quick_sort(li, left, right):
    if left < right:
        mid = partition(li, left, right)
        quick_sort(li, left, mid-1)
        quick_sort(li, mid+1, right)
        print(li)
quick_sort(li, 0, len(li)-1)     #结果:[1, 2, 3, 4, 5, 6, 7, 8, 9]

快速排序时间复杂度:O(nlogn),空间复杂度:O(logn)

 

未完。。。。

Guess you like

Origin www.cnblogs.com/wangcuican/p/12094060.html