python sorting and searching algorithms

First, search


1. sequential search

Configuration data is stored in a linear or sequential relations, sequential access can find

def sequential_search(ilist, item):
    pos = 0

    while pos < len(ilist):
        if ilist[pos] == item:
            return pos
        else:
            pos = pos + 1

    return -1

2. Binary Search

For the ordered sequence table using a binary search, each item starts from the middle, so that each half of the remaining items may be excluded

def binary_search(ilist, item):
    first = 0
    last = len(ilist)
    while first <= last:
        mid_point = (first + last) // 2
        if ilist[mid_point] == item:
            return mid_point
        else:
            if item < ilist[mid_point]:
                last = mid_point - 1
            else:
                first = mid_point + 1
    return -1

Recursive version

def binary_search(ilist, item):
    if len(ilist) == 0:
        return -1
    else:
        midpoint = len(ilist) // 2
        if ilist[midpoint] == item:
            return midpoint
        else:
            if item < ilist[midpoint]:
                return binary_search(ilist[:midpoint-1], item)
            else:
                return binary_search(ilist[midpoint+1:], item)

Find 3.Hash

 Data stored in a hash table, a hash table for each position is generally referred to as a groove, the groove can be generally sequentially numbered from 1, the mapping between the data and the groove called a hash function . Load factor

λ = occupied slots / table size, the table below λ = 6/11. Search a number only need to use a hash function to calculate the slot number data can be found.

Some common hash function: remainder number (only need data by table size), summation of the packet (the data into blocks of equal size, and then added together to obtain the hash value of the block), middle-square method (square data first, and then extracting a portion of the data results)

Due to the limited number of slots, so there will be conflict, conflict resolution: OpenAddressed (to cycle hash table until you find an empty slot), linear probe (order to find an empty slot, for example: 1,2,3,4, 5, the disadvantage is prone to aggregation), re-hashing the groove (groove skipped, uniform distribution of conflict, for example: 1,3,5,7,9), the second probe (using a constant skip values, such as 1,4 , 9, 16), the list (see below)

Specific implementation can use Python's dictionary

Second, sorting


1. Bubble Sort

As the name suggests, like a bubble, like float or sink to the bottom like a heavy object, like, every trip, there will be ordering one extreme position to reach the final.

def bubble_sort(nlist):
    for pass_num in range(len(nlist)-1, 0, -1):
        exchanges = False
        for i in range(pass_num):
            if nlist[i] > nlist[i+1]:
                exchanges = True
                nlist[i], nlist[i+1] = nlist[i+1], nlist[i]
        if not exchanges:
            return

2. Select Sort

Every choice on the final one extreme position. Compared bubble sort, reducing the number of exchanges.

def selection_sort(nlist):
    for fill_slot in range(len(nlist)-1, 0, -1):
        position_of_max = 0
        for location in range(1, fill_slot+1):
            if nlist[location] > nlist[position_of_max]:
                position_of_max = location

        nlist[fill_slot], nlist[position_of_max] = nlist[position_of_max], nlist[fill_slot]

3. Insertion Sort

Like playing cards when inserted card draw, successive increase in the number of ordered lists.

def insertion_sort(nlist):
    for index in range(1, len(nlist)):
        current_value = nlist[index]
        position = index
        while position > 0 and nlist[position-1] > current_value:
            nlist[position] = nlist[position-1]
            position = position - 1
        nlist[position] = current_value

4. Shell sort

Shell sort the list by the original is decomposed into a plurality of smaller sub-lists to improve insertion sort, insertion sort used for each sub-list are sorted.

def shell_sort(nlist):
    sub_list_count = len(nlist) // 2
    while sub_list_count > 0:
        for start_position in range(sub_list_count):
            gap_insertion_sort(nlist, start_position, sub_list_count)
        sub_list_count = sub_list_count // 2


def gap_insertion_sort(nlist, start, gap):
    for i in range(start + gap, len(nlist), gap):
        current_value = nlist[i]
        position = i
        while position >= gap and nlist[position - gap] > current_value:
            nlist[position] = nlist[position - gap]
            position = position - gap

        nlist[position] = current_value

5. merge sort

A recursive algorithm, to keep the list into half, then sort the sub-list, then merge. Divide and rule strategy.

def merge_sort(nlist):
    if len(nlist) > 1:
        mid = len(nlist) // 2
        left_half = nlist[:mid]
        right_half = nlist[mid:]
        merge_sort(left_half)
        merge_sort(right_half)
        i, j, k = 0, 0, 0
        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                nlist[k] = left_half[i]
                i += 1
            else:
                nlist[k] = right_half[j]
                j += 1
            k += 1
        while i < len(left_half):
            nlist[k] = left_half[i]
            i += 1
            k += 1
        while j < len(right_half):
            nlist[k] = right_half[j]
            j += 1
            k += 1

6. Quick Sort

 Select a value as a pivot value, then as a reference, while the ratio of large series becomes small while the ratio of two parts, each determined location of the pivot sorting trip value.

def quick_sort(nlist):
    quick_sort_helper(nlist, 0, len(nlist) - 1)


def quick_sort_helper(nlist, first, last):
    if first < last:
        split_point = partition(nlist, first, last)
        quick_sort_helper(nlist, first, split_point - 1)
        quick_sort_helper(nlist, split_point + 1, last)


def partition(nlist, first, last):
    pivot_value = nlist[first]
    left_mark = first + 1
    right_mark = last
    while True:
        while left_mark <= right_mark and nlist[left_mark] <= pivot_value:
            left_mark = left_mark + 1
        while right_mark >= left_mark and nlist[right_mark] >= pivot_value:
            right_mark = right_mark - 1
        if right_mark < left_mark:
            break
        else:
            nlist[left_mark], nlist[right_mark] = nlist[right_mark], nlist[left_mark]
    nlist[first], nlist[right_mark] = nlist[right_mark], nlist[first]

    return right_mark

At last:

Sorting Algorithm

Worst Time Analysis The average time complexity stability Space complexity
Bubble Sort O (N 2 ) O (N 2 ) stable O (1)
Quick Sort O (N 2 ) O(n*log2n) Unstable O (Log 2 N) ~ O (N)
Selection Sort O (N 2 ) O (N 2 ) Unstable O (1)
Binary tree sort O (N 2 ) O(n*log2n) Different top O (n)

Insertion Sort

O (N 2 ) O (N 2 ) stable O (1)
Heapsort O(n*log2n) O(n*log2n) Unstable O (1)
Shell sort O O Unstable O (1)

 

 

Guess you like

Origin www.cnblogs.com/hwnzy/p/10972714.html