How to achieve Python (list) sort?

Sort, many programming languages ​​is often a problem. Similarly, in Python, how to achieve the sort it? (Hereinafter sort are achieved based on a list)

First, the use of built-in functions to sort Python

Python has a built-in function to achieve sorting, you can call them directly implement sorting

Python lists have a built-in  list.sort() way to directly modify the list. There is also a  sorted() built-in function, it will build a new ranking list from one iteration object.

1.sort () function:

list.sort(cmp=None, key=None, reverse=False)

The meaning of the parameters are:

  1. CMP - optional parameter, if this parameter is a method of using the parameter designated for sorting.

  2. Key - mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.

  3. Reverse - collation, Reverse descending = True,  Reverse ascending = False (default).

Enter the default list can be sorted, for example:

list=[1,2,4,5,3]
list.sort()
print(list)
>>>[1,2,3,4,5]

2.sorted () function:

sorted(iterable, cmp=None, key=None, reverse=False)

among them:

  1. Iterable - iterables.

  2. CMP - compare function, the two parameters, parameter values are taken from the subject may be iterative, this function must comply with the rules is greater than 1 is returned, it is less than -1, is equal to 0 is returned.

  3. Key - mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.

  4. Reverse - collation, reverse = True descending, reverse = False ascending (default).

Similarly, the use of sorted () function can sort the list, for example:

list=[1,2,4,5,3]
print(sorted(list))
>>>[1,2,3,4,5]

sort () and sorted (), although similar, can achieve the sort function, but they are very different:

sort () and sorted () the difference:

sort () method is applied in a list, sorted () may be ordered to operate all objects iterations.

list of sort () method returns a list of the existing operation, no return value, the built-in function sorted () method returns a new list, rather than operation performed on the basis of the original.

Second, using common sorting algorithm to sort

Like other high-level functions, Python can also use the algorithm to sort the use of general statements.

1. Bubble Sort

  Bubble sort is the most commonly seen sorting algorithm is a very basic sorting algorithm. Its implementation is thinking: two adjacent elements are compared, then the larger elements into the back (in a forward direction), in a comparison after the largest element is placed on the last position, like a fish in the water spouting air bubbles becomes larger and larger in the process of rising,

def bubble_sort(list):
    count = len(list)
    for i in range(count):
        for j in range(i + 1, count):
            if list[i] > list[j]:
                list[i], list[j] = list[j], list[i]
    return list

2. Select Sort

  Select the sort of thinking is: the first round, when all of the elements and the first element of comparison, if larger than the first element, and the first element on the exchange, in this round of relatively exhausted, to find the smallest element; the second round, when all of the elements and the second element are compared to identify elements of the second position, and so on.

def selection_sort(list):
    length = len(list)
    for i in range(length - 1, 0, -1):
        for j in range(i):
            if list[j] > list[i]:
                list[j], list[i] = list[i], list[j]
       return list

3. Insertion Sort

  The idea is to sort insert is inserted into a data already sorted ordered data to obtain a new, plus a number of sequenced data, sorting algorithm is suitable for small amounts of data, the time complexity is O (n ^ 2). Stable sorting method. Insertion algorithm to sort the array is divided into two parts: the first part contains all the elements of the array, but except for the last element (let the arrays that have a space inserted position), while the second part contains only one element of this (i.e., the element to be inserted). After completion of the first sorting section, then the last element has been inserted into the first portion sorted

def insert_sort(list):
    count = len(list)
    for i in range(1, count):
        key = list[i]
        j = i - 1
        while j >= 0:
            if list[j] > key:
                list[j + 1] = list[j]
                list[j] = key
            j -= 1
    return list

4. Quick Sort

  Quick sort of thinking is: a trip by ordering the data to be sorted into two independent parts, the part where all the data than the other part of all data to be small, then this method of data for the two parts separately fast sorting, sorting the entire process can be recursively, in order to achieve the whole data into an ordered sequence.

def quick_sort(list, left, right): 
    if left >= right:
        return list
    key = lists[left]
    low = left
    high = right
    while left < right:
        while left < right and list[right] >= key:
            right -= 1
        lists[left] = lists[right]
        while left < right and list[left] <= key:
            left += 1
        list[right] = list[left]
    list[right] = key
    quick_sort(list, low, left - 1)
    quick_sort(list, left + 1, high)
    return list

LST1 = raw_input (). Split () function call #
lst = [int(i) for i in lst1]
#lst = input()
quick_sort(lst,0,len(lst)-1)
for i in range(len(lst)):
    print lst[i],

5. Shell sort

  Hill is a sort insertion sort. Also known as narrow increment sort, direct insertion Ranking algorithm more efficient improved version. Hill sorting non-stationary sorting algorithm. The method because DL. Shell made so named in 1959. Shell sort is the subject of pressing the recording packet in increments, the use of direct insertion sort each sorting algorithm; With increment is gradually reduced, more and more keywords each comprising, when reduced to an increment, the entire file is divided into just one set, the algorithm will terminate.

def shell_sort(list):
    count = len(list)
    step = 2
    group = count / step
    while group > 0:
        for i in range(group):
            j = i + group
            while j < count:
                k = j - group
                key = list[j]
                while k >= 0:
                    if list[k] > key:
                        list[k + group] = list[k]
                        list[k] = key
                    k -= group
                j += group
        group /= step
    return list

Guess you like

Origin www.cnblogs.com/Y-xp/p/11668278.html