Bubble sort, select sort, insert sort, quick sort

Source: Internet
Author: User

Bubble sort (Bubble sort)

Bubble sort (Bubble sort) is a simpler sort algorithm in the field of computer science.

It repeatedly visited the sequence to be sorted, two elements in a note, and exchanged them if they were in the wrong order. The job of visiting the sequence is to repeatedly know that there is no exchange in need, that is, the sequence is already sorted.

The name of the algorithm is because the larger the element will slowly "float" to the top of the sequence, hence the name.

Data_set = [9,1,22,31,45,3,6,2,11] Loop_count = 0for J in range (Len (data_set)): For    I in range (len (data_set)-j-1) : # 1 is because each match is I and I +1, not minus 1, the last comparison will be beyond the list to get the range,-j because, each time the big loop represents a sort of a maximum value,
On the last side of the list, the next loop will not have to be sorted if data_set[i] > data_set[i+1]: #switch tmp = data_set[i] Data_set[i] = DATA_SET[I+1] data_set[i+1] = tmp loop_count +=1 print (data_set) print (data_set) print ("Loop times", loop _count)

  

Select sort

The algorithm works by selecting the smallest unsorted item and then swapping it with the item in the next position to be Filled.

The selection sort works as follows:you look through the entire array for the smallest element, once your find it you swap It (the smallest element) with the first element of the array. Then the smallest element of the remaining array (an array without the first element) and swap it with the SE Cond element. Then your look for the smallest element in the remaining array (an array without first and second elements) and swap it wit H The third element, and so on. Example,the worst-case runtime complexity is O (n2).

Data_set = [9,1,22,31,45,3,6,2,11] smallest_num_index = 0 #初始列表最小值, default = First Loop_count = 0for j in range (Len (data_set)): 
   for i in range (J,len (data_set)):        if data_set[i] < Data_set[smallest_num_index]: #当前值 is smaller than the minimum value chosen before, change it to the minimum            Smallest_num_index = i        loop_count +=1    Else:        print ("Smallest num is", Data_set[smallest_num_index])        tmp = Data_set[smallest_num_index]        Data_set[smallest_num_index] =  Data_set[j]        data_set[j] = tmp     print (Data_set)    print ("Loop times", Loop_count)

Method Two:

Thinking: Using the index

Insert Sort

The basic idea of inserting a sort (insertion sort) is to divide the list into 2 parts, a sorted part on the left, an unsorted part on the right, a loop through the entire list, and each time a record to be sorted is inserted into the appropriate position in the previously ordered subsequence by its keyword size. Until all records have been inserted to complete.

The insertion sort is very similar to an entire poker.

At the beginning of the card, the left hand is empty, face down on the table. Next, touch a card from the table one at a time and insert it into the right position in the left hand card. In order to find the right position of this card, compare it to the hand that you already have in your hands from right to left. At any time, the cards in the left hand are orderly.

Perhaps you do not realize, but in fact your thinking process is like this: now caught a 7, put it and hand cards from right to left in turn, 7:10 small, should go to the left, 7:5 big, good, plug here. Why compare 10 and 5 to determine the position of 7? Why not compare the 4 and 2 on the left? Because there's an important premise here: The cards in hand are already in order. Now I inserted 7, the hand is still in the order of the cards, the next time to catch the card can also be inserted by this method. The same is true for programming an array for insertion, but unlike inserting a poker, it is not possible to insert another unit between two adjacent storage cells, so the data after the insertion point is moved back one cell at a later step.

Li = [3,34,5,34,23,45,56,3]for i in Range (Len (LI)): While    I >0 and li[i] < Li[i-1]:        # tmp = li[i]        # li[i ] = li[i-1]        # li[i-1] = tmp        li[i],li[i-1] = li[i-1],li[i]        I-= 1        print (LI) # print (LI)

  

[3, 5, 34, 34, 23, 45, 56, 3]
[3, 5, 34, 23, 34, 45, 56, 3]
[3, 5, 23, 34, 34, 45, 56, 3]
[3, 5, 23, 34, 34, 45, 3, 56]
[3, 5, 23, 34, 34, 3, 45, 56]
[3, 5, 23, 34, 3, 34, 45, 56]
[3, 5, 23, 3, 34, 34, 45, 56]
[3, 5, 3, 23, 34, 34, 45, 56]
[3, 3, 5, 23, 34, 34, 45, 56]

Quick sorting (Quick sort)

Set to sort the array is a[0] ... A[n-1], the first arbitrary selection of data (usually the first number of the array) as the key data, and then all the smaller than the number of it in front of it, all the larger than its number is placed behind it, this process is called a fast sort of a trip. It is important to note that fast sorting is not a stable sorting algorithm, which means that the relative position of multiple identical values may change at the end of the algorithm

Note: In the file to be sorted, if there are more than one record of the same keyword, the relative order between the records with the same key is maintained, the sorting method is stable, and if the relative order of the records with the same keyword changes, it is said that this sort method is unstable.
It is important to note that the stability of the sorting algorithm is for all input instances. That is, in all possible input instances, if an instance makes the algorithm not satisfy the stability requirement, the sorting algorithm is unstable.

Sort Demo

In fact, it's divided into two groups, left and right.

The example assumes that the user has entered the following array: Subscript0    1    2    3    4    5Data6    2    7    3    8    9Create variable i=0(Point to First data), j=5(point to last data), k=6(the value assigned to 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 is moved to Subscript 3, Complete the first comparison: subscript0    1    2    3     4    5Data3    2    7    6    8    9I=0j=3k=6then, 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 point to the subscript 3 of the data of 6 to exchange, the data state into the following table: subscript0    1    2    3    4    5Data3    2    6    7    8    9I=2j=3k=6It 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 (=6the number on the left is smaller than it is, and the number on the right of K is bigger than it: subscript0    1    2    3    4    5Data3    2    6    7    8    9If 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. 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. 
View Code

#_ *_coding:utf-8_*___author__ = ' Alex Li ' def quick_sort (array,left,right): ':p Aram array::p Aram left: The first of the list    An index:p Aram right: The index of the last element of the list: return: "If left >=right:return low = left high = right Key = Array[low] #第一个值 while low < high: #只要左右未遇见 when low < high and Array[high] > key: #找到列表右边比key大 The value of high-= 1 #此时直接 The key (Array[low]) with the larger than the Array[high] to exchange array[low] = Array[high] Arra Y[high] = key while low < high and Array[low] <= key: #找到key左边比key大的值, why is this <= rather than <?            You have to think ...  Low + = 1 #array [Low] = #找到了左边比k大的值, put Array[high] (should be just saved as key) with this larger than key Array[low] to exchange Array[high] = Array[low] array[low] = key Quick_sort (array,left,low-1) #最后用同样的方式对分出来的左边的小组进行同上的做法 Quick_sort (array,low+ 1, right) #用同样的方式对分出来的右边的小组进行同上的做法 if __name__ = = ' __main__ ': array = [96,14,10,9,6,99,16,5,1,3,2,4,1,13,26,18,2,45,3   4,23,1,7,3,22,19,2] #array = [8,4,1, 6, 2, 3, 9,5, 7,1, 8,10, +] print ("Before sort:", array) Quick_sort (Array,0,len (array)-1) Print ("-------final-------") print (array)

  

Bubble sort, select sort, insert sort, quick sort

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.