Several common algorithms for sorting

Source: Internet
Author: User

Algorithm definition

Algorithm (algorithm) is an accurate and complete description of the solution, a series of clear instructions to solve the problem, the algorithm represents a systematic approach to describe the problem-solving strategy mechanism

The merits and demerits of an algorithm can be measured by the complexity of space and time .

an algorithm should have the following seven important characteristics:

① (finiteness): The poor nature of the algorithm means that the algorithm must be able to terminate after a finite number of steps are performed; ② certainty (definiteness): Each step of the algorithm must have a definite definition; ③ input (Input): An algorithm has 0 or more inputs, To characterize the initial situation of the operand, the so-called 0 inputs refer to the algorithm itself setting the initial conditions; ④ output: An algorithm has one or more outputs to reflect the results of processing the input data. No output algorithm is meaningless; ⑤ feasibility (effectiveness): Any calculation step performed in the algorithm can be decomposed into a basic executable step, that is, each calculation step can be completed in a limited time (also known as validity); ⑥ efficiency (high Efficiency): Performs fast, consumes less resources, ⑦ robustness (robustness): responds correctly to data.
Complexity of Time

In computer science, the time complexity of the algorithm is a function, it quantitatively describes the algorithm's running time, time complexity commonly used large o symbol (Big O notation)

is a mathematical symbol used to describe the progressive behavior of a function; Big O, in short, can be thought of as "order of" (approximately)

For details, see: http://www.cnblogs.com/alex3714/articles/5910253.html

Http://www.cnblogs.com/alex3714/articles/5474411.html

Common sort

Name

Complexity of

Description

Note

Bubble sort
Bubble Sort

O (N*n)

Consider the elements to be sorted as "bubbles" that are vertically arranged, smaller elements lighter and thus upward

Insert Sort

Insertion Sort

O (N*n)

Remove elements from each other in the sequence of sequenced elements, and then scan them in the appropriate position

Initially, the ordered sequence of elements is empty

Select sort

O (N*n)

The smallest element is first found in the unordered sequence, placed at the start of the sort sequence, and then continues to look for the smallest element from the remaining unsorted elements and then to the end of the sort sequence. recursively.

Quick Sort

Quick Sort

O (n *log2 (n))

First select the middle value, then put smaller than it on the left, large on the right side (the specific implementation is to find from both sides, find a pair after exchange). The process is then used separately on both sides (recursion).

Heap Sort Heapsort

O (n *log2 (n))

A sort algorithm constructed using the data structure of the heap (heaps). A heap is an approximate complete binary tree structure that satisfies the heap property at the same time: that is, the child node's key value or index is always less than (or greater than) its parent node.

Approximate complete binary tree

Hill sort

SHELL

O (N1+£)

0<£<1

Select a step (step), and then sort by the cell with the step in intervals. Recursively, the step size becomes smaller until it is 1.

Box sorting
Bin Sort

O (N)

Set up a number of boxes, the key is equal to K records are loaded into the K-box (allocation), and then sequentially by serial number of non-empty boxes connected together (collected).

One of the allocation sorts: the order is implemented through the assign and collect procedures.

First, bubble sort

It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order.

The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted.

Ideas:

The next two values are compared, the larger values are placed on the right, then the comparison!

Data_set = [9, 1, 22, 31, 45, 3, 6, 2, 11]# first type # for J in Range (Len (data_set)): # for     i in range (len (data_set)-j-1) : #         if data_set[i] > data_set[i+1]:##             tmp = data_set[i]#             data_set[i] = data_set[i+1]#             data_set[i+1] = tmp#             # Data_set[i], data_set[i+1] = data_set[i+1], data_set[i]  # can simplify the above three lines of code into a line of #     print (data_set) # Print ( Data_set) # Second count = Len (data_set) for I in range (0, count): for    J in range (i + 1, count):        if data_set[i] > Dat A_SET[J]:            data_set[i], data_set[j] = Data_set[j], data_set[i]print (Data_set)

The time complexity shows that his code complexity will grow exponentially with n increasing, and judging his time complexity at 0 (n2)

Second, insert sort

The basic operation of inserting a sort is to insert a data into the ordered data that is already sorted, so as to get a new sequential data with a number plus one, the algorithm is suitable for the ordering of a small amount of data, and the time complexity is O (n^2).

is a stable sorting method. The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except for the last element (so that the array has one more space to insert),

The second part contains only this element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence.

Ideas:

A list is divided by default to the left for the sort, we take the first element example, his left is all sorted well, his right is not sorted well, if the right element is less than the left-hand ordered list of elements to insert him into the appropriate position

Data_list = [34, 45, 7, 89, 43, 2, 6, 4, 12,-9, 34, 88,]# First: # for I in range (len (data_list)): # while     i > 0 and Data_list[i] < data_list[i-1]:#         tmp = data_list[i]#         data_list[i] = data_list[i-1]  # If the while condition is set to replace the current value with his last value #         data_list[i-1] = tmp#         I-= 1  # When the above conditions are not true #     print (data_list) # print (Data_ List) # second type: # for I in range (1, Len (data_list)): #     key = data_list[i]# for     j in range (I-1,-1,-1): #         if Data_li ST[J] > key:#             data_list[j + 1] = data_list[j]#             data_list[j] = key# print (data_list) # Third count = Len (data_list ) for I in range (1, count):    key = Data_list[i]    j = i-1 while    J >= 0:        if DATA_LIST[J] > Key:
   data_list[j + 1] = Data_list[j]            data_list[j] = key        J-= 1print (data_list)
Iii. Choice of sorting

Basic idea: The 1th trip, in order to sort records R1 ~ R[n] To select the smallest record, it and R1 Exchange, 2nd trip, in order to sort records R2 ~ R[n] In the selection of the smallest record, it and R2 exchange;

And so on, the first pass selects the smallest record in the sorted record R[i] ~ R[n], swapping it with r[i], so that the ordered sequence continues to grow until all sorts are completed.

Ideas:

For the first time, the element from the leftmost part of the list is array[0], the right loop, and the element less than array[0] found in the right element is exchanged until the right loop is finished.

The second time, the first element on the left is now the smallest, from array[1], and the rest of the array[1:-1] in contrast, in turn!

Contrast:

The difference between sorting and bubbling sorting is that the bubble sort is a comparison of the adjacent 22, but the selection sort is the "contrast element" on the left and the value in the list on the right is compared!

Data_list = [34, 45, 7, 89, 43, 2, 6, 4, 12,-9, 34, 88,]# the first # for K in range (len (data_list)): #     Set_len_index = k#
   for I in range (K, Len (data_list)): #         if data_list[i] < data_list[set_len_index]:#             Set_len_index = i#     TMP = data_list[set_len_index]#     Data_list[set_len_index] = data_list[k]#     data_list[k] = tmp#     print (data_ List) s# print (data_list) # Second count = Len (data_list) for I in range (0, count):    min = i  # assuming default first value minimum for    j in Ra Nge (i + 1, count): If        data_list[min] > Data_list[j]:            min = j  # If smaller, record subscript for smaller elements    Data_list[min] , data_list[i] = Data_list[i], data_list[min]print (data_list)
Iv. Quick Sort

Set to sort the array is a[0] ... A[N-1], first select any data (usually the first number of the array) as the key data, and then put all the smaller than the number in front of it,

All the larger numbers are put behind it, and this process is called a quick sort of a trip. It is important to note that fast sorting is not a stable sorting algorithm, that is to say,

The relative position of multiple identical values may change at the end of the algorithm. His time complexity is:O (nlogn) ~0 (n2)

Example of sorting:

Suppose the user enters an array like this:

Create a variable i=0 (point to First Data) [I location red flag], j=5 (point to the last data) [J Location Blue Small flag], k=6 (assigned to the value of the first data).

We're going to move all the numbers smaller than K to the left of K, so we can start looking for a smaller number than 6, starting with J, from right to left, constantly diminishing the value of the variable J, we find the first subscript 3 of the data is smaller than 6, so the data 3 is moved to subscript 0 position, the subscript 0 of the data 6 to subscript 3, the first comparison is completed:

I=0 j=3 k=6

Then, to start the second comparison, this time to become bigger than the K, and to go after the search. Sliding scale variable I, found that the data of subscript 2 is the first larger than the K, so with the subscript 2 of the data 7 and J points to the subscript 3 of the data of 6 to exchange, the data state into the following table:

i=2 j=3 k=6

It is said that the above two comparisons are a cycle. Then, the variable J is decremented again, repeating the above cycle comparison. In this example, we do a loop and find I and J "Meet": they all point to subscript 2. So, the first time the comparison is over. The results are as follows, usually K (=6) the number on the left is smaller than it, the number of K right is larger than it:

If I and J do not meet, then sliding scale I find large, not yet, and then diminishing J to find small, so repeated, continuous circulation. Attention to judgment and search is carried out at the same time.

Then, the data on both sides of the K, and then the process is divided into the above, until no further grouping.

Note: The first time quick sort does not directly get the final result, only the number smaller than K and K is divided into the two sides of K. In order to get the final result,

You need to perform this step again on an array of subscript 22 edges, and then decompose the array until the array is no longer decomposed (only one data) to get the correct result.

Data_list = [7, 2, 6, 4, 9, 6,]def Quick_sort (Data_list, left, right): If the left    >= rig HT:        return data_list    key = Data_list[left] Low    = left    ,        right and left < right: while L EFT < right and Data_list[right] >= key: Right-            = 1        data_list[left] = Data_list[right] While left        < R Ight and Data_list[left] <= key: Left            + + 1        data_list[right] = Data_list[left]    data_list[right] = key< C13/>quick_sort (Data_list, Low, left-1)    Quick_sort (data_list, left + 1, high)    return data_listif __name__ = = ' __main__ ':    quick_sort (data_list, 0, Len (data_list)-1)    print (data_list)

def quick_sort (array, left, right): "':p Aram array::p Aram Left: The first index of the list:p Aram right: The index of the last element of the list: Retu RN: "If left >= right:return low = left high = right key = Array[low] # first value while low &L T High: # As long as the left and right did not meet while low < higher and Array[high] > key: # Find the value of the list to be greater than key up to 1 array  [Low] = Array[high] # at which point the key (Array[low]) is directly exchanged with the larger Array[high] array[high] = key while low < high and Array[low] <= Key: # Find the key to the left of the value larger than key, why this is <= instead of <?            You have to think ... Low + = 1 Array[high] = Array[low] # Find the left side of the value greater than K, put Array[high] (this time should have just saved the key) with this larger than the key Array[low] to exchange Array[low ] = key Quick_sort (array, left, low-1) # Finally, in the same way to the split-out panel on the other side of the same procedure Quick_sort (array, low+1, right) # in the same way to split out the The group of the same practice if __name__ = = ' __main__ ': array = [96, 14, 10, 9, 6, 99, 16, 5, 1, 3, 2, 4, 1,-123,-876, 13, 26, 18, 2, 45   , 1, 3, 7, 2] print ("Before sort:", array) Quick_sort (array, 0, Len (array)-1) print ("-------final-------") print (array) 

Subsequent updates ...

Several common algorithms for sorting

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.