Comparison and analysis of common sorting algorithms

Source: Internet
Author: User

A summary of common sorting algorithms

The following mainly from the basic concept of sorting algorithm, the principle of the algorithm from the time complexity, space complexity, the stability and speed of the algorithm and other aspects of the analysis and Comparison. Depending on the size of the problem to be sorted (number of records n), the amount of memory space required during the sorting process is different, thus dividing the sorting algorithm into two categories:"inner sort","outside sort".

In order : The data elements are all stored in the Computer's random memory ram when Sorting.

out of order: the number of records to be sorted is so large that the memory cannot hold all the records at once, and the sorting process of the external access is required during the sorting process.

Let's look at the taxonomy of common sorting algorithms (see figure 1-1)

Figure 1-1 Common sorting algorithms

The algorithm of ordering correlation in two

2.1 Insert Sort

Core Idea: Insert a data element to be sorted into the appropriate position in the previously sorted sequence so that the data elements remain in order until all the data elements are sorted are Inserted.

2.1.1 Direct Insert Sort

Core Idea: The key code of the first Data element to be inserted is the i-1, i-2, i-3, ... The values of the data elements are compared in order, and this linear search method finds the insertion position of the first data element, and the data elements in the original position move back in order until they are all Sorted.

In the direct insert sort, the same key data element will keep the original position unchanged, so the algorithm is stable, the worst value of time complexity is Square order o (n2), the spatial complexity is constant order o (l).

Python source Code:

#-------------------------direct insertion sort--------------------------------def insert_sort (data_list):  #遍历数组中的所有元素, Where the No. 0 index element is sorted by default, starting from 1 for    x in range (1, len (data_list)):    #将该元素与已排序好的前序数组依次比较, If the element is small, the    #range is exchanged (x-1,-1,- 1): reverse cycle from x-1 to 0        for I in range (x-1,-1,-1):        #判断: if eligible then swap if            data_list[i] > data_list[i+1]:                temp = data_list[i+1]                data_list[i+1] = data_list[i]                data_list[i] = Temp

2.1.2 Hill Sort

Core Idea: is the record according to the index of a certain increment grouping, each group using the direct insertion sorting algorithm to sort; as the increment decreases gradually, each group contains more and more keywords, when the increment is reduced to 1 o'clock, the entire file is divided into a group, the algorithm Terminates.

Hill sort time complexity would be better than O (n2), however, The first insert sort is stable in multiple insertions, but in different insertion sorts, the same elements may move in their own insert sort, so the hill sort is unstable.

  Python Source Code:

#-------------------------hill sort-------------------------------def Insert_shell (data_list):    #初始化step值, Here we use half of the sequence length to assign the    group = int (len (data_list)/2)    #第一层循环: Change the group value to group the list while group    > 0:    # Below: sorting grouped data using the idea of direct insertion sorting        #range (group,len (data_list)): starting from group for        I in range (group, len (data_list)):            # Range (x-group,-1,-group): starts with the selected element starting at x-group, with the interval between each comparison element group for            J in range (i-group, 1,-group):                # If two elements of the group meet the interchange criteria, then Exchange if                data_list[j] > data_list[j+group]:                    temp = data_list[j+group]                    data_list[ j+group] = data_list[j]                    data_list[j] = temp        #while循环条件折半        group = int (group/2)

2.2 Select Sort

core Idea: every scan, select the smallest or largest element of the key code from the data element to be sorted, placing it in the final order of the sequential sequence, until all the data elements to be sorted are Exhausted.

2.2.1 Direct Select Sort

Core Idea: Select the smallest data element for each location, i.e. select the smallest element to swap with the element at the first position, and then select the smallest element in the second position in the remaining element to swap until the second and last element is Compared.

According to its basic idea, whenever a scan, if the current element is smaller than an element, and this small element appears in an element equal to the current element, then their position has been exchanged, so the direct selection of the order is not stable, the time complexity of the square order O (n2), the spatial complexity of O (l).

  Python Source Code:

#-------------------------direct Select Sort-------------------------------def select_sort (data_list): #依次遍历序列中的每一个元素    For I in range (0, len (data_list)): #将当前位置的元素定义此轮循环当中的最小值        minimum = data_list[i] #将该元素与剩下的元素依次比较寻找最小元素 for        J in Range (i+1, len (data_list)):            if data_list[j] < minimum:                temp = data_list[j];                data_list[j] = minimum;                Minimum = temp# assigns the actual minimum value obtained after comparison to the current position        data_list[i] = minimum

2.2.2 Heap Sort

An effective improvement on the direct selection of sorting when the heap is Sorted.

Core Idea: all the data is built into a heap, the largest data is at the top of the heap, and then the data elements of the top of the heap are exchanged with the last element of the sequence ; Then the heap is rebuilt, the data is exchanged, and the sequence of all data elements is Achieved. The completion of heap sequencing requires two actions: heap and heap adjustments, so repeatedly.

Heap ordering may cause two elements of the same value to be interchanged, so it is unstable, with an average time complexity of 0 (nlog2n)and a space complexity of O (l).

Python Source Code:

#-------------------------heap sort--------------------------------#********** get left and right leaves node **********def (i): return 2*i + 1def Right (i): return 2*i + 2#********** to adjust the large top heap ********** #data_list: length of sequence to be adjusted: series Lengths I: Node Def adjust_max_heap to be adjusted (d        ata_list,length,i): #定义一个int值保存当前序列最大值的下标 largest = i# perform the loop operation: two tasks: 1 find the subscript for the maximum value, 2. The maximum value is exchanged with the parent node while 1: #获得序列左右叶子节点的下标 left, right = leave (i), right (i) #当左叶子节点的下标小于序列长度 and the value of the left leaf node is greater than the parent node, assigns the subscript to largest if (leave < Length) and (d ata_list[left] > Data_list[i]): largest = left #print (' leaves node ') else:largest = i# when the subscript of the right leaf node is less than the sequence length and the value of the right leaf node is greater than the parent node, the subscript value of the right leaf node is assigned to largest if (r < Length) and (data_list[right] > Data_list [largest]): largest = right #print (' left leaf node ') #如果largest不等于i indicates that the current parent node is not the maximum value and needs to exchange the value if (largest! =            i): temp = data_list[i] data_list[i] = data_list[largest] data_list[largest] = Temp            i = Largest#print (largest) continue else:break#********** build a big Top heap **********def build_max_heap (data_list) : length = Len (data_list) for x in range (int ((length-1)/2), -1,-1): adjust_max_heap (data_list,length,x) #****** Heap sort **********def Heap_sort (data_list): #先建立大顶堆, The maximum value is guaranteed to be at the root node, and the parent node value is greater than the leaf node Build_max_heap (data_list) # I: The length of the sequence in the current heap. initialized to the length of the sequence i = Len (data_list) #执行循环: 1. Each time the top element of the heap is removed at the end of the sequence (len-1,len-2,len-3 ...) # 2.        Adjust the heap so that it continues to satisfy the nature of the large top heap, note the real-time modification of the length of the sequence in the heap while i > 0:temp = data_list[i-1] data_list[i-1] = data_list[0] data_list[0] = temp# heap length minus 1 i = i-1# adjustment large Top heap adjust_max_heap (data_list, i, 0)

2.3 Exchange Sort

Core Idea: as the name implies, is a set of data elements to be sorted, according to the order of the position of each other to compare their key code, if it is reversed, then exchange the two data elements until the sequence of data elements in Order.

2.3.1 Bubble Sort

Core Idea: for a set of data elements to be sorted, each data element as a weight of the bubble, according to the principle of light bubbles can not be under the heavy bubbles, the top-down of all the elements in the order of the next two to compare and adjust the next, so that the heavier elements to sink, lighter Upward.

According to the basic idea, only if the order of the two elements is the opposite of the ordering requirement, they will be reversed, otherwise they remain unchanged, so the bubble sort is stable. The time complexity is square order o (n2)and the spatial complexity is o (l).

Python Source Code:

#-------------------------bubble sort--------------------------------def bubble_sort (data_list):    length = Len (data_ List) #序列长度为length, you need to perform length-1 wheel exchange for    x in range (1,length): #对于每一轮交换, all the left and right elements in the sequence are compared # each round of exchange, since the last element of the sequence must be the largest, So each round loops to the unordered position of the sequence for        i in range (0,length-x):            if data_list[i] > data_list[i+1]:                temp = data_list[i]                data_list[i] = data_list[i+1]                data_list[i+1] = Temp

2.3.2 Quick Sort

Quick sorting is an improvement in the nature of bubble sorting.

Core Idea: is an in-place sort, divide-and-conquer, large-scale recursive algorithm. That is, after a trip to ensure that the datum point of the data element of the left element is smaller than it, the right element is larger than it, and then recursive method to deal with the left and the other side of the elements, until the datum point of only one Element.

An unstable algorithm for fast sequencing, with a worst-case time complexity of square order o (n2), and a spatial complexity of o (log2n).

Python Source Code:

#-------------------------quick Sort--------------------------------#data_ List: the sequence to be sorted; start sort starts at the end of the index,end sequence index# for the length of the sequence: start = 0;end = Length-1def Quick_sort (data_list,start,end            ): if start < end:i, j, pivot = start, end, data_list[start] while I < J: #从右开始向左寻找第一个小于pivot的值                 While (i < j) and (data_list[j] >= pivot): j = j-1# moves the value less than pivot to the left if (i < j): data_list[i] = data_list[j] i = i+1# from left to right look for the first value greater than pivot while (i < j) and (d ata_list[i] < pivot): i = i+1# moves values greater than pivot to the right if (i < j): data_list[j] = dat a_list[i] j = j-1# After the end of the loop, description i=j, when the left side of the value is all smaller than pivot, the right value is all greater than the position of the Pivot#pivot move correctly, then only the left and right side of the sequence call this function further ordering # recursive call function        : Sequence on left: from 0 to I-1//right sequence: from i+1 to end data_list[i] = pivot# left sequence continue sorting Quick_sort (data_list,start,i-1) #右侧序列继续排序 Quick_sort (data_list,i+1,end) 

2.4 Merge Sort

Core Idea: the data series are recursively divided into short sequences, that is, divide 1 into 2,2 into 4, then decompose in sequence, and then sort these groupings when decomposed into only 1 groups. Then merge back into the original sequence, merging until the original sequence is all Sorted.

The merge process ensures that two equal current elements are stored in front of the result sequence, so that the merge sort is stable, with a time complexity of o (nlog2n)and an o (n)space Complexity.

Python Source Code:

#-------------------------merge Sort--------------------------------#这是合并的函数 # will sequence data_list[first...mid] and sequence data_list[ mid+1...last] to merge def Mergearray (data_list,first,mid,last,temp): #对i, The j,k is assigned i,j,k = first,mid+1,0# when the left and right sides of the number are compared, Take the smaller number while (i <= mid) and (j <= last): if data_list[i] <= data_list[j]: temp[k] = data_list  [i] i = i+1 k = k+1 else:temp[k] = data_list[j] j = j+1 k = k+1# if the left sequence has a few while (i <= mid): temp[k] = data_list[i] i = i+1 k = k+1# If the right sequence has a few while (j & lt;= last): temp[k] = data_list[j] j = j+1 k = k+1# assigns the ordered element in temp to the data_list backlog sequence so that it is partially ordered for the X in RA        Nge (0,k): data_list[first+x] = temp[x]# This is a function of grouping def merge_sort (data_list,first,last,temp): if first < last: Mid = (int) ((first + last)/2) #使左边序列有序 merge_sort (data_list,first,mid,temp) #使右边序列有序 merge_sort (data_li St,mid+1,last,temp) #将两个有序序列合并 MergeArray (data_list,first,mid,last,temp) # merge sorted function def merge_sort_array (data_list): empty list of #声明一个长度为len (data_list) temp = Len ( Data_list) *[none] #调用归并排序 merge_sort (data_list,0,len (data_list) -1,temp)

2.5 Base Sort

Core Idea: the first is the low sort, then the collection ; followed by a high ranking, and then collected ; And so on, until the highest bit.

Python Source Code:

#-------------------------base Sort--------------------------------#确定排序的次数 # The order of sorts is related to the number of digits of the maximum number in the sequence Def radix_sort_nums ( data_list): maxnum = data_list[0] #寻找序列中的最大数 for x in Data_list:if maxnum < X:maxnum = x# OK sequence The number of bits of the largest element times = 0 while (maxnum > 0): maxnum = (int) (maxnum/10) times = times+1 return times# found  Num data from low to high POS bit def get_num_pos (num,pos): return ((int) (num/(10** (pos-1)))%10# cardinality sort def radix_sort (data_list): count = 10*[none] #存放各个桶的数据统计个数 bucket = len (data_list) *[none] #暂时存放排序结果 # from low to high, execute loop for POS in range (1,radix_sort _nums (data_list) +1): #置空各个桶的数据统计 for x in range (0,10): count[x] = 0 #统计当前该位 (digit, 10 bit, hundred ...)             Number of elements for X in range (0,len (data_list)): #统计各个桶将要装进去的元素个数 j = Get_num_pos (int (data_list[x)), POS)  count[j] = count[j]+1 #count [i] indicates the right boundary index of the first bucket for x in range (1,10): count[x] = count[x] + count[x-1] #将数据依次装入桶中 for X in Range (len (data_list) -1,-1,-1): #求出元素第K位的数字 j = Get_num_pos (data_list[x],pos) #放入对应的桶中, count[      J]-1 is the right boundary index of the J-bucket bucket[count[j]-1] = data_list[x] #对应桶的装入数据索引-1 count[j] = count[j]-1 # Pour out the data in the allocated bucket, which is already an ordered table for x in range (0,len (data_list)): data_list[x] = bucket[x]

  

third, the sequencing algorithm measurement

Figure 3-1 Common sorting algorithm test statistics

Comparison and analysis of sorting algorithms

Table 4-1 Comparison of various sorting algorithms

[ Direct Insert sort] is an improvement over the bubbling sort, faster than a bubbling sort, but only for a small (1000) amount of data

[ Hill sort] is relatively simple, suitable for small data volume (less than 5000) of the sorting, faster than the direct insertion sort, bubble sort fast, So the hill sort is suitable for small data volume, sorting speed is not a high order.

[ Direct Selection sort] and bubble sort algorithm, suitable for the case of small n value, but also is the initial stage of the development of the sorting algorithm, in the actual application of the probability is Small.

[ heap sort] is more suitable for sorting of millions of data and more, in which case a stack overflow may occur when using a recursive design for quick sorting and merging of Sorts.

[ bubble sort] is the slowest sorting algorithm, is the initial stage of the development of the sorting algorithm, the probability of using the algorithm in practical applications is relatively small.

[ quick sort] is a recursive, fastest sorting algorithm, but is not a good choice in the case of limited memory, and for a basic ordered sequence of data sequences, fast sorting becomes slower.

[ merge sort] is faster than heap ordering, but requires more storage space.

[ Cardinal sort] applies to large-scale N-value situations, but only applies to integer ordering, and if the floating-point numbers are sorted in cardinal order, the storage format of the floating-point numbers must be clarified, and then mapped to integers in some way, and then mapped back, the process is Complex.

Reference:

Time complexity and spatial complexity table of various sorting algorithms

Eight sorting algorithms

Python implementations of eight sorting algorithms (http://python.jobbole.com/82270/)

Comparison and analysis of common sorting algorithms

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.