[Data Structure]——Exercises related to sorting algorithms

1. Multiple choice questions

Question Type 1 (Insertion Sort)

1. Direct insertion sort

1. Direct insertion sorting of n elements requires () processing.
A, n
B, n+1
C, n-1
D, 2n

Analysis: (C)
Direct insertion sorting is to insert the sequence to be sorted into the sorted subsequence according to the size of the keyword, and continue until the entire sequence is ordered. Therefore, direct insertion sorting is performed on n elements, and a total of n-1 elements are inserted. times, need to be done n-1趟.

2. For direct insertion sorting of 5 different data elements, the maximum number of comparisons required is ().
A, 8
B, 10
C, 15
D, 25

Analysis: (B)
Consider the worst case scenario for the maximum number of comparisons that need to be made, that is, the maximum number of comparisons when the sequence elements are arranged in reverse order. Since at this time, 1, 2, 3,..., n-1 times need to be compared from front to back. So n(n-1)/2=(5×4)/2=10.

3. Perform direct insertion sorting on n elements. The time complexity in the best case is () and the time complexity in the worst case is ().
A. O(n), O(n 2 )
B. O(n 2 ), O(n)
C. O(n), O(n)
D. O(n 2 ), O(n 2 )

Analysis: (A)
最好情况Down, that is, the sequence elements are all in order. At this time, only the elements need to be compared without moving the elements. The number of comparisons is times n-1, so 最好时间复杂度it is O(n); and 最坏情况down, that is, when the sequence elements are arranged in reverse order, the number of comparisons at this time is and the number of moves both reach the maximum value, n(n-1)/2so 最坏时间复杂度it is O(n 2 ); considering the average situation, the total number of comparisons and moves is about n 2 /4, so the direct insertion sort 时间复杂度is O(n 2 ).

4. Direct insertion sorting of n elements, the space complexity is ()
A, O(n)
B, O(1)
C, O(n 2 )
D, O(log 2 n)

Analysis: (B)
Directly insert the sorting code as follows:

/*直接插入排序(由小到大)*/
void InsertSort(int r[],int n) {
    
    
	int i,j,temp;
	for(i=1; i<n; ++i) {
    
    
		temp=r[i];	//将要插入的元素暂存在temp中
		for(j>=0,j=i-1;temp<r[j];--j)
			r[j+1]=r[j];	//向后挪一位 
		r[j+1]=temp;	//找到插入位置并插入
	}
}

Since only auxiliary variables are used in direct insertion sort, the space complexity is O(1).

5. If the sorted element sequence is basically ordered, the most efficient sorting algorithm is ().
A. Simple selection sort
B. Quick sort
C. Direct insertion sort
D. Merge sort

Analysis: (C)
Since the sequence is basically ordered, the sorting algorithm with the smallest average complexity should be selected. Direct/halved insertion sort, simple selection sort, and bubble sort are all simple sorting algorithms. The average time complexity is O(n 2 ) , but in the best case, direct insertion sort and bubble sort can reach O( n), half insertion sort can reach O(nlog 2 n); heap sort, quick sort, and merge sort are all improved sorting algorithms, so their time complexity is O(nlog 2 n), in the best case It can reach O(nlog 2 n).

2. Half-way insertion sort

1. Perform halved insertion sorting on n elements. The time complexity in the best case is () and the time complexity in the worst case is ().
A. O(n 2 ), O(nlog 2 n)
B. O(n), O(n 2 )
C. O(n 2 ), O(n)
D. O(nlog 2 n), O(n 2 )

Analysis: (D)
Compared with direct insertion sort, halved insertion sort reduces the number of comparisons of elements, and its number of moves is the same as direct insertion sort. First find the insertion position of the current element in half, the time complexity at this time is O(nlog 2 n), and then move all the elements after the insertion position, the time complexity at this time is O(n 2 ), so 最好时间复杂度it is O(nlog 2 n); in the worst case, it 最坏时间复杂度is O(n 2 ); considering the average case, the half insertion sort 时间复杂度is still O(n 2 ).

2. Perform half-way insertion sorting on n elements, the space complexity is ()
A, O(n)
B, O(1)
C, O(n 2 )
D, O(log 2 n)

Analysis: (B)
The half insertion sort code is as follows:

/*折半插入排序*/
void Binary_InsertSort(int r[],int n) {
    
    
	int i,j,temp,low,high,mid;
	for(i=1; i<=n; i++) {
    
    	 
		temp=r[i];	//将要插入的元素暂存在temp中
		low=0;
		high=i-1;	//low和high为折半查找的范围 
		while(low<=high) {
    
    
			mid=(low+high)/2;	//mid取中间点 
			if(r[mid]>temp)	//查找左半子表 
				high=mid-1;
			else	//查找右半子表 
				low=mid+1;
		}
		for(j=i-1; j>=high+1; j--)	//先后移动元素,空出位置留给插入元素 
			r[j+1]=r[j];
		r[j+1]=temp;	//找到插入位置并插入	
	}
}

Since only auxiliary variables are used in half insertion sort, the space complexity is the same as direct insertion sort, which is also O(1).

3. Hill sorting

1. Perform Hill sorting on the initial data sequence (8, 3, 9, 11, 2, 1, 4, 7, 5, 10, 6). If the first sorting result is (1, 3, 7, 5, 2, 6, 4, 9, 11, 10, 8), the second sorting result is (1, 2, 6, 4, 3, 7, 5, 8, 11, 10, 9), then the increments (intervals) used in the two sorting passes are () in sequence.
A, 3, 1
B, 3, 2
C, 5, 2
D, 5, 3

Analysis: (D)
Insert image description here
Insert image description here
Therefore, the increments used in the two sorting passes are 5 and 3 respectively.

2. Hill sorting uses () for intra-group sorting.
A. Direct insertion sort
B. Half insertion sort
C. Quick sort
D. Merge sort

Analysis: (A)
Hill sorting is also called 缩小增量sorting. It sorts by selecting a certain increment. Its essence is insertion sorting. The sequence is divided into several subsequences by increments, and then for each 子序列进行直接插入排序, when all sequences are basically When sorting, perform another direct insertion sort to complete.

3. In the following sorting, the unstable sorting algorithm is ().
A. Bubble sort
B. Direct insertion sort
C. Hill sort
D. Merge sort

Analysis: (C)
Since the relative positions may change after being divided into different subsequences, Hill sorting is unstable.

Question type 2 (exchange sorting)

1. Bubble sorting

1. Perform bubble sorting on n elements. The time complexity in the best case is (), and the time complexity in the worst case is () A. O(n 2
) , O(n)
B. O( n), O(n 2 )
C, O(n), O(n)
D, O(n 2 ), O(n 2 )

Analysis: (B)
In the best case, that is, the result to be sorted is exactly the sorted result. At this time, the number of comparisons is n-1, the number of moves and the number of exchanges are both 0, so it is 最好时间复杂度O(n); and in the worst case, that is The arranged sequence is just opposite to the initial sequence and is arranged in reverse order. At this time, n-1 sorting is required. In the i-th sorting, ni comparisons are required, that is, the number of comparisons = the number of exchanges = n(n-1)/ 2. Since each exchange will move the element 3 times to exchange the element, that is, the number of moves is 3n(n-1)/2, so it is 最坏时间复杂度O(n 2 ). Considering the average case, the bubble sorting is 时间复杂度O (n 2 );

2. If the bubble sort algorithm is used to sort the sequence {10, 14, 26, 29, 41, 52} from large to small, () comparisons are required.
A, 3
B, 10
C, 15
D, 25

Analysis: (C)
Element 52 bubbles to the front and is compared 5 times; element 41 bubbles to the front and is compared 4 times..., so the total number of comparisons is 5+4+3+2+1=15 times.

3. If the bubble sort algorithm is used to sort the sequence {5, 2, 6, 3, 8} in ascending order, and the comparison is performed from back to front, the result of the first pass of bubble sort is ().
A. {2, 5, 3, 6, 8}
B. {2, 5, 6, 3, 8}
C. {2, 3, 5, 6, 8}
D. {2, 3, 6, 5, 8}

Analysis: (A)
First, 8>3, consistent with ascending order, no exchange;
3<6, not consistent with ascending order, exchange, this time is {5, 2, 3, 6, 8};
2<3, consistent with ascending order, no exchange;
5 >2, does not comply with ascending order, exchange, this time is {2, 5, 3, 6, 8};
therefore, the result of the first bubble sort is {2, 5, 3, 6, 8}.

4. (Multiple choice) Among the following algorithms, the one that can determine the final sorting position of an element in each sorting pass is ().
A. Direct insertion sort
B. Half-way insertion sort
C. Hill sort
D. Bubble sort
E. Quick sort
F. Simple selection sort
G. Heap sort

Analysis: (D、F、G)
冒泡排序, 简单选择排序, 堆排序each pass can determine the final sorting position of an element (each pass in heap sort forms an overall ordered subsequence), but 快速排序only determines the final position of the pivot element in each pass of sorting.

2. Quick sort

1. Quickly sort n elements. If the number of elements in the left and right subranges obtained by each division is equal or only differs by one, the time complexity of sorting is ().
A. O(1)
B. O(nlog 2 n)
C. O(n 2 )
D. O(n)

Analysis: (B)
快速排序It is an improved algorithm for bubble sorting. It is also called partition exchange sorting. It implements the sorting idea through multiple partitioning operations. In each sorting pass, a keyword is selected as the pivot. The pivot divides the sequence to be sorted into two parts. Elements smaller than the pivot are moved to the front, and elements larger than the pivot are moved to the back. This is A quick sort is performed, and then the two parts are continued to be sorted according to the pivot division rules until each area has only one element, and finally the entire sequence is ordered.
When each division is very even, 最好时间复杂度it is O(nlog 2 n); and when the sequence is originally in forward or reverse order, the performance is the worst at this time, because each time the element closest to the edge is selected, 最坏时间复杂度it is O(n 2 ); so quick sorting 平均时间复杂度is O(nlog 2 n).

2. The quick sort algorithm is most unfavorable to its strengths in () situations.
A. The amount of data to be sorted is too large
. B. The data to be sorted contains multiple identical values
. C. The number of data to be sorted is an odd number.
D. The data to be sorted is basically in order.

Analysis: (D)
The time complexity of the quick sort algorithm is related to the number of recursion levels, which is O (n × the number of recursion levels), that is, it depends on the recursion depth. If each division is more uniform, the recursion depth will be lower; the more uneven it is, the recursion will be The deeper the depth. It can be seen that, 当初始序列有序或逆序时in quick sort 性能最差, each time it selects the elements closest to both sides of the sequence, and one side of the divided area is empty, so the 初始序列越接近无序或基本上无序more efficient the algorithm is at this time; the closer it is to ordering or basically ordering, the algorithm The lower the efficiency.

3. Among the following four sorting algorithms, the one with the least average number of keyword comparisons is ().
A. Insertion sort
B. Selection sort
C. Quick sort
D. Merge sort

Analysis: (C)
The best time complexity of quick sort is O(nlog 2 n), which is closest to its required time in the average case and far from the worst case O(n 2 ), so quick sort is all internal sorting algorithms Among them 平均性能最优的排序算法, its average number of comparisons is the least.

4. Quickly sort n keywords. The maximum recursion depth is () and the minimum recursion depth is ().
A, n; 1
B, n; log 2 n
C, log 2 n; 1
D, log 2 n; nlog 2 n

Analysis: (B)
Since the recursion in the quick sort code needs to be assisted, it requires a large space, which is special compared with other sorting algorithms. Its space complexity is related to the number of recursion levels (depth of the stack), which is O(递归层数).

二叉树的最大/小高度:
若将n个要排序的元素组成一个二叉树,
这个二叉树的层数就是递归调用的层数(栈的深度),
由于在n个结点的二叉树中,其最小高度=⌊ log2n ⌋
(以2为底n的对数然后再向上取整,取比自己大的最小整数),
其最大高度=n。

Therefore, the situation is the same as that of a binary tree. The best case is the minimum height, which is ⌊ log 2 n ⌋ levels, that is 最小递归深度; and the worst case is the maximum height, which is n levels, that is 最大递归深度.

5. When quickly sorting a sequence of n elements, the space complexity is ().
A. O(n)
B. O(n 2 )
C. O(log 2 n)
D. O(1)

Analysis: (C)
The best case is the minimum height, which is ⌊ log 2 n ⌋, that is, the minimum recursion depth, which 最好空间复杂度is O(log 2 n); and the worst case is the maximum height, which is the maximum recursion depth, which is n layers. At this time 最坏空间复杂度it is O(n), so 平均空间复杂度it is O(log 2 n).

6. Assume a set of initial record keyword sequences {5, 8, 6, 3, 2}, and the result of a quick sort from large to small based on the first record keyword 5 is ().
A. {2, 3, 5, 8, 6}
B. {2, 3, 5,
6, 8} C. {3, 2, 5, 8, 6}
D. {3, 2, 5, 6, 8}

Analysis: (B)
Take the first element 5 as the pivot, leave the original position empty, i and j point to the head and tail elements of the sequence, and start the first quick sort: the entire process ensures that the left side of the i pointer is an element smaller than the pivot element
Insert image description here
. , the right side of the j pointer is the element ( ) that is larger than the pivot element j指针找小于,i指针找大于. First, for j, search from right to left to find an element smaller than the pivot element. If found, j stops. Since element 2 is greater than pivot element 5, the value of j is exchanged with the value of i: Then for i
Insert image description here
Insert image description here
, Search from left to right and find an element that is larger than the pivot element. If found, i stops. Since element 2 is smaller than element 2, continue to the right and stop at element 8. 8>5: j continues to move. Since element 8 is larger
Insert image description here
Insert image description here
than Continue to the left and stop at element 3, 3<5. At this time, j and i exchange:
Insert image description here
Insert image description here
.........Repeat the steps:
Insert image description here
Insert image description here
j continues to move, at this time i and j meet, and the final position is the position of the pivot element:
Insert image description here
Therefore The result of quick sort is {2, 3, 5, 6, 8}.

Question type three (selective sorting)

1. Simple selection sorting

1. Among the following four sorting methods, the number of comparisons in the sorting process has nothing to do with the initial state of the sequence ().
A. Selection sort
B. Insertion sort
C. Quick sort
D. Bubble sort

Analysis: (A)
The number of comparisons in selection sort is always independent of the initial sequence.

2. Perform simple selection sorting on n elements, the time complexity is ().
A. O(n)
B. O(n 2 )
C. O(log 2 n)
D. O(nlog 2 n)

Analysis: (B)
In each simple selection sorting process, each time 从未排序的序列中选取当前元素最小的元素, it is used as the i, i+1,... element ( ) of the ordered subsequence 加入到已排好序列的末尾, and is carried out in sequence, that is, exchanged with the first element, Exchanges are performed sequentially until one element remains. At this time, the entire sequence is in order. Each simple selection sort can determine the final position of an element.

Therefore, compared with other sorting algorithms, 比较次数与初始序列无关the number of comparisons for each element is n-1, n-2,..., 2, 1, that is, n(n-1)/2=n 2 /2, so it is 时间复杂度always is O(n 2 ).

2. Perform simple selection sorting on n elements, the number of comparisons and the number of moves are () respectively.
A. O(n), O(log 2 n)
B. O(log 2 n), O(n 2 )
C. O(n 2 ), O(n)
D. O(nlog 2 n), O( n)

Analysis: (C)
The number of comparisons of simple selection sorting has nothing to do with the initial sequence and is always O(n 2 ), while the number of moves is related to the initial sequence. When the initial sequence is 正序时为最好情况, at this time 移动次数最少, there is no need to move, and the number of moves is 0; and when the sequence 逆序时为最坏情况, at this time 移动次数最多, is 3(n-1) times, so the average number of moves is O(n).

2. Heap sort

1. Heap sort is a () sort.
A. Swap
B. Select
C. Insert
D. Merge

Analysis:(B)

2. Among the following four sequences, which one is heap().
A. 70, 40,
60, 25, 10, 20, 15, 5 B. 70, 60, 40, 5, 25, 20, 15, 10
C. 70, 60, 25, 10, 20, 40, 15, 5
D, 70, 40, 60, 5, 20, 25, 15, 10

Analysis: (A)
Heap sorting uses a heap tree for sorting. It can be regarded as a complete binary tree. Each node in the tree is greater than or equal to the value of its two child nodes. The root node is the minimum value in the heap tree. Or the maximum value, which corresponds to the small root heap and the large root heap, which is defined in the following table:

heap condition
dagendui In a complete binary tree,根≥左,右
small root pile In a complete binary tree,根≤左,右

Draw the sequence in the question through a heap. The first element in the sequence is the root node of the heap, all of which are element 70: It
Insert image description here
can be seen that options B, C, and D do not meet the definition of a large root heap, and they are not a small root heap. , so the correct option is A.

3. Assume that the element sequence {7, 3, 5, 9, 1, 12} is heap sorted and a small root heap is used, then the initial heap composed of initial data is ().
A. 1, 3, 5,
7, 9, 12 B. 1, 3, 5, 9,
7, 12 C. 1, 5, 3, 7, 9, 12
D. 1, 5, 3, 9, 12 ,7

Analysis: (B)
The initial small root heap does not satisfy the small root heap, so adjustments are made:
for a small root heap, check whether all non-terminal nodes meet the requirements of the large root heap (root node ≤ left child, right child), if not, then Make adjustments: If the element of the current node is greater than the smaller element of the left or right child, exchange the current node with the smaller element to make the subtree a heap. If the element exchange destroys the next level If the heap order does not meet the properties of the heap, continue to adjust downwards.

Since N=6, we can get the number of non-leaf nodes i≤⌊N/2 ⌋=⌊6/2 ⌋=3. Check whether all non-terminal nodes meet the requirements of the small root heap, that is, check the result of i≤3 Click and check in order from bottom to top.
Insert image description here
i=3, node 5 meets the requirements and no adjustment is needed.
i=2, node 3 does not meet the requirements, so it is exchanged with the smaller element of the left or right child, that is, node 3 is exchanged with 1, as follows: i=1, node 7 does not meet the requirements, that is,
Insert image description here
with The smaller element 1 among the child nodes is exchanged, as follows:
Insert image description here
It can be seen that the adjusted node 7 does not meet the conditions and needs to be adjusted again. Node 7 is exchanged with the smaller element among its child nodes, that is, 7 is exchanged with 3. As follows:
Insert image description here
Therefore, the final initial heap sequence is {1, 3, 5, 9, 7, 12}.

4. Assume that an initial heap is (1, 5, 3, 9, 12, 7, 15, 10). After performing the first heap sort, the result obtained by rebuilding the heap is ().
A, 3, 5, 7, 9, 12, 10, 15, 1
B, 3, 5, 9, 7, 12, 10, 15,
1 C, 3, 7, 5, 9, 12, 10, 15, 1
D, 3, 5, 7, 12, 9, 10, 15, 1

Analysis: (A)
It can be seen from the initial heap sequence that the heap is a small root heap (in a complete binary tree, 根≤左,右) as follows: The steps
Insert image description here
for heap sorting 堆排序are as follows: After establishing the root heap, exchange the top element of the heap with the last element of the heap , the top element of the heap enters the ordered sequence and reaches the final position (being discharged from the unordered sequence, in line with the process of selection sort), and then continues to adjust the remaining unordered sequence, in order..., until the unordered sequence With the last element remaining in the sequence, the entire sequence is now in order, and heap sorting ends.

In the first pass, the top element of the heap is exchanged with the last element of the heap, and the top element of the heap is added to the ordered subsequence, that is, 1 and 10 are exchanged: Obviously, at this time, the complete binary tree does not meet the definition of a small root heap and needs to be adjusted
Insert image description here
. :
Insert image description here
Insert image description here
The adjustment is completed. At this time, after the first heap sorting is performed, the result sequence obtained by rebuilding the heap is:
{3, 5, 7, 9, 12, 10, 15, 1}.

5. Construct an initial heap of n records, its time complexity is (), perform heap sorting, its time complexity is ().
A. O(n), O(log 2 n)
B. O(n), O(nlog 2 n)
C. O(n 2 ), O(log 2 n)
D. O(n 2 ), O( nlog 2 n)

Analysis: (B)
初始建堆The time complexity of The elements need to be compared twice, and each pass does not exceed O(h)=O(log 2 n). That is, the time complexity of heap sorting is O(nlog 2 n), so the heap sorting 时间复杂度is O(n)+O( nlog 2 n)=O(nlog 2 n).

6. Insert the keywords 6, 9, 1, 5, 8, 4, and 7 into the initially empty large root heap H, and the resulting H is ().
A, 9, 8, 7, 6, 5, 4,
1 B, 9, 8, 7, 5, 6, 1, 4
C, 9, 8, 7, 5, 6, 4,
1 D, 9, 6 ,7,5,8,4,1

Analysis: (B)
After each keyword is inserted in sequence, when the definition of a large root heap is not satisfied, adjustments are made:
Insert image description here
Insert image description here
Insert image description here
Insert image description here
Insert image description here
so the final H is 9, 8, 7, 5, 6, 1, 4.

7. The time complexity of inserting a new element into a heap with n nodes is (), and the time complexity of deleting an element is ().
A. O(log 2 n), O(log 2 n)
B. O(nlog 2 n), O(nlog 2 n)
C. O(1), O(log 2 n)
D. O(n), O(nlog 2 n)

Analysis: (A)
For 堆进行插入操作timing, place the node to be inserted at the end of the heap. After insertion, the entire complete binary tree still needs to meet the requirements of the heap. The node is adjusted upward. Each ascending operation requires comparing elements once. Since the complete binary tree The height of is h=⌊log 2 n⌋+1, so inserting a new element into a heap of n nodes 时间复杂度is O(log 2 n).

When the 堆进行删除操作time is right, the position of the deleted node will be vacated. At this time, the element at the end of the heap needs to be filled in to this position, and then adjusted down to the appropriate position. Each downward adjustment requires comparing the elements once or twice. The deletion operation also depends on The height of the tree 时间复杂度is O(log 2 n).

8. When performing heap sort on a sequence of n elements, the additional storage space required is ().
A. O(n)
B. O(n 2 )
C. O(log 2 n)
D. O(1)

Analysis: (D)
After establishing the root heap, exchange the top element of the heap with the last element of the heap. The top element of the heap enters the ordered sequence and reaches its final position (it is discharged from the unordered sequence, consistent with the process of selection sort), and then Continue to adjust the remaining unordered sequence, and proceed in sequence... until the last element remains in the unordered sequence. At this time, the entire sequence is ordered, and heap sorting ends. The code for heap sort is as follows:

/*堆排序*/
void HeapSort(int r[],int n){
    
    
	int i,temp;
	for(i=n/2;i>=1;i--)		//建立初始堆 
		Adjust(r,i,n);
	for(i=n;i>1;i--){
    
    	//进行n-1次循环,完成堆排序 
		temp=r[1];	//将堆中最后一个元素与堆顶元素交换,将其放入最终位置 
		r[1]=r[i];
		r[i]=temp;
		Adjust(r,1,i-1); 	//对剩下的无序序列进行调整 
	}
}

Since only a constant number of auxiliary units are required, the space complexity is O(1).

9. If you only want a partially sorted sequence before the 10th smallest element in a sequence of 1000 elements, the () method is the fastest.
A. Bubble sort
B. Quick sort
C. Hill sort
D. Heap sort

Analysis: (D)
Usually when taking k largest/smallest elements from a large amount of data, heap sorting is generally used. Since it only needs to adjust the large/small root heap 10 times, the time is proportional to the height of the formed tree.

Question type four (merge and sort)

1. Among the following sorting algorithms, the one that takes up the most auxiliary space is ().
A. Quick sort
B. Merge sort
C. Heap sort
D. Bubble sort

Analysis: (B)
The code for merge sort is as follows:

/*归并*/
void Merge(int r[],int low,int mid,int high) {
    
    
	int *r1=(int *)malloc((high-low+1)*sizeof(int));	//辅助数组r1 
	for(int k=low; k<=high; k++)
		r1[k]=r[k];	//将r中的所有元素复制到r1中 
	for(i=low,j=mid+1,k=i; i<mid&&j<=high; k++) {
    
    //low指向为第一个有序表的第一个元素,j指向第二个有序表的第一个元素
		if(r1[i]<=r1[j])	//比较r1的左右两段中的元素 
			r[k]=r1[i++];	//将较小值复制到r1中 
		else
			r[k]=r[j++];
	}
	while(i<=mid)
		r[k++]=r1[i++];	//若第一个表没有归并完的部分复制到尾部 
	while(i<=high)
		r[k++]=r1[j++];	//若第二个表没有归并完的部分复制到尾部 
}

/*归并排序*/
void MergeSort(int r[],int low,int high) {
    
    
	if(low<high) {
    
    
		int mid=(low+high)/2;	//划分 
		MergeSort(r,low,mid);	//对左有序子表递归 
		MergeSort(r,mid+1,high);	//对右有序子表递归 
		Merge(r,low,mid,high);	//归并
	}
}

The recursive work stack is used in this algorithm, 递归工作栈and the space complexity is O(log 2 n). In addition, an auxiliary array is used, and the space complexity is O(n), so the merge sort algorithm 空间复杂度is O(n). The average space complexity of quick sort is O(log 2 n), and the space complexity of heap sort and bubble sort is O(1).

2. Among the following sorting algorithms, the order of magnitude of the number of comparisons during the sorting process has nothing to do with the initial state of the sequence ().
A. Quick sort
B. Merge sort
C. Heap sort
D. Insertion sort

Analysis: (B)
Two-way merge sort, simple selection sort, and radix sort 比较次数have nothing to do with the state of the initial sequence.

3. For k-way merge sorting, the number of keyword comparisons required for each selected element is () times.
A, 1
B, k
C, k+1
D, k-1

Analysis: (D)
In the two-way merge sort, one element is taken out from the two divided sequences for keyword comparison, so selecting an element requires comparing the keyword once, that is, in the k-way merge sort, each time an element is selected The number of times the keyword needs to be compared is k-1 times.

4. For two-way merge sorting, the order of magnitude of the number of merge passes is ().
A. O(n)
B. O(n 2 )
C. O(nlog 2 n)
D. O(log 2 n)

Analysis: (D)
For N elements k路归并排序, the number of sorting passes m satisfies k m =N, that is, m=⌈log k N⌉, so for 二路归并排序, where k=2, so the order of magnitude of the number of passes for the two-way merge sort is O(log 2n ).

5. Merge and sort n elements, the time complexity is ().
A. O(nlog 2 n)
B. O(n 2 )
C. O(n)
D. O(log 2 n)

Analysis: (A)
In merge sort, the number of comparisons has nothing to do with the initial sequence, that is, the divided subsequence has nothing to do with the initial sequence. Since the time complexity of each merge sort is O(n), the entire merge sort has a total of ⌈log 2 n⌉ times . So it 时间复杂度's O(nlog2n).

6. If you want to sort 1000 elements and it is required to be fast and stable, it is best to use the () sorting method.
A. Direct insertion sort
B. Heap sort
C. Merge sort
D. Quick sort

Analysis: When the number of elements to be sorted is large, a faster sorting algorithm with an (C)
average time complexity of O(nlog 2 n) should be used, including quick sort, heap sort and merge sort, as follows:

Sorting Algorithm space complexity average time complexity best time complexity Worst time complexity sort by stability applicability
Quick sort At best, O(log 2 n); at worst, O(n); on average, O(log 2 n) O(n log 2 n) O(n log 2 n) O(n 2 ) Internal sorting (In-place) × sequential storage
Heap sort O(1) O(n log 2 n) O(n log 2 n) O(n log 2 n) Internal sorting (In-place) × sequential storage
merge sort O(n) O(n log 2 n) O(n log 2 n) O(n log 2 n) External sorting (Out-place) Sequential storage and chained storage

Since the speed of quick sort depends on whether the sequence is randomly distributed, when the initial sequence is randomly distributed, the average time of quick sort is the fastest, so it is unstable; in addition, because the same elements at the back may be adjusted to the front during sorting , so heap sort is also unstable; therefore merge sort can be used.

Question type five (radix sorting)

1. Among the following sorting algorithms, the sorting algorithm that does not require keyword comparison is ().
A. Quick sort
B. Heap sort
C. Merge sort
D. Radix sort

Analysis: (D)
Radix sorting is different from the previous sorting algorithm. It is not sorted based on comparison and moving elements, but based on the idea of ​​multi-keyword sorting. It divides a logical keyword into multiple keywords. It is based on keywords. They are sorted by size, so there is no need to compare keywords.

2. Suppose the array S[]={93, 946, 372, 9, 146, 151, 301, 485, 236, 327, 43, 892} uses least significant digit first (LSD) radix sorting to arrange S into ascending sequence. After one pass of allocation and collection, the elements before element 372 and immediately after it are ().
A. 43,892
B. 236, 301
C. 301, 892
D. 485, 301

Analysis: (C)
The lowest digit is used first, so the first pass is sorted based on the single digit size of the keyword. The sequence is as follows:
Insert image description here
{151, 301, 372, 892, 93, 43, 485, 946, 146, 236, 327, 9},
so the elements before and immediately after element 372 are 301 and 892.

2. Application questions

Question Type 1 (Insertion Sort)

Example 1: For the initial sequence {46, 74, 53, 14, 26, 38, 86, 65, 27, 34}, the sorting result is an increasing direct insertion sort, and the sorting result of each sorting pass is written.

Direct insertion sort :
(1) The first pass, 74>46, consistent with increment, no insertion operation, the sequence is:
{ , 53, 14, 26, 38, 86, 65, 27, 34}; (2) The second pass trip, because 53<74 does not conform to increment, 74 moves backward one position, and 53 is inserted into the original position of 74. At this time, the sequence is: {, 14, 26, 38, 86, 65, 27, 34 }; ( 3) In the third pass, since 14<74 and 14<53 and 14<46 do not conform to increment, 74, 53, and 46 are moved backward one position in turn, and 14 is inserted into its original position respectively. The sequence at this time is: { , 26, 38, 86, 65, 27, 34}; (4) The fourth pass, since 26<74 and 26<53 and 26<46, does not conform to increment, so 74, 53, and 46 are moved backward one in turn. position, and 26 is inserted into its original position respectively, the sequence at this time is: { , 38, 86, 65, 27, 34}; (5) The fifth pass, since 38<74 and 38<53 and 38<46, no It is consistent with increment, so 74, 53, and 46 are moved backward one position in turn, and 38 is inserted into its original position respectively. The sequence at this time is: {, 86, 65, 27, 34 }; (6) The sixth pass, 86> 74, conforms to increment, no insertion operation is performed, the sequence is: { , 65, 27, 34}; (7) The seventh pass, since 65<86 and 65<74, does not conform to increment, so 86 and 74 are moved backward by one After position 65 is inserted into its original position respectively, the sequence at this time is: { , 27, 34}; 46,74
46,53,74
14,46,53,74
14,26,46,53,74
14,26,38,46,53,74
14,26,38,46,53,74,86
14,26,38,46,53,65,74,86
(8) The eighth trip, because 27<86 and 27<74 and 27<65 and 27<53 and 27<46 and 27<38, does not comply with the increment, so 86, 74, 65, 53, 46, 38 are backward After moving one position and inserting 27 into its original position, the sequence at this time is: { , 34}; (9) The ninth pass, because 34<86 and 34<74 and 34<65 and 34<53 and 34<46 And 34<38 does not comply with increment, so 86, 74, 65, 53, 46, 38 are moved one position backward, and 34 is inserted into its original position respectively. At this time, the sequence is: { }, and the direct insertion sorting ends at this time , the final result is {14, 26, 27, 34, 38, 46, 53, 65, 74, 86}. 14,26,27,38,46,53,65,74,86
14,26,27,34,38,46,53,65,74,86

Question type 2 (half-way insertion sort)

Example 2: For the initial sequence {13, 38, 49, 65, 76, 97, 27, 49*}, the sorting result is an increasing half insertion sort, and write the sorting result of each sorting pass.

Half insertion sort :
Insert image description here
Since the first 6 elements in the sequence are arranged in ascending order, low=0, high=5, that is, low points to 13, high points to 97, mid=⌊(low+high/2)⌋, rounded down, that is Take the largest integer smaller than itself.
(1) In the first trip, low=0, high=5, mid=⌊(0+5)/2⌋=⌊2.5⌋=2, the element with subscript 2 is 49. Since 27<49, 27 should be Insert into the left half of mid, that is, to the left of element 49;

At this time, low=0 remains unchanged, change high=mid-1=2-1=1, mid=⌊(0+1)/2⌋=⌊0.5⌋=0, and the element with subscript 0 is 13, because 27>13, so 27 should be inserted into the right half of mid, that is, to the right of element 13;

At this time, high=1 remains unchanged, low=mid+1=0+1=1 is changed, mid=⌊(1+1)/2⌋=⌊1⌋=1, and the element with subscript 1 is 38, because 27<38, so 27 should be inserted into the left half of mid, that is, to the left of element 38;

At this time, low=1 remains unchanged, and high=mid-1=1-1=0 is changed. Since low>high, the first half search is completed, and the insertion position of 27 is after the element with subscript high=0, that is, 13 Later, the result is { , 49*}. (2) In the second pass, low=0, high=6, mid=⌊(0+6)/2⌋=⌊3⌋=3, the element with subscript 3 is 49, since 27<49*, so 27 It should be inserted into the left half of mid, that is, to the left of element 49; at this time, low=0 remains unchanged, change high=mid-1=3-1=2, mid=⌊(0+2)/2⌋=⌊ 1⌋=1, the element with subscript 1 is 27. Since 49*>27, 49* should be inserted into the right half of mid, that is, to the right of element 27; 13,27,38,49,65,76,97

Insert image description here

At this time, high=2 remains unchanged, low=mid+1=1+1=2 is changed, mid=⌊(2+2)/2⌋=⌊2⌋=2, and the element with subscript 2 is 38, because 49*>38, so 49* should be inserted into the right half of mid, that is, to the right of element 38;

At this time, low=2 remains unchanged, and high=mid-1=2-1=1 is changed. Since low>high, the second half search ends, and the insertion position of 49* is after the element with subscript low=2, that is, 38 behind, so the final result is { }. 13,27,38,49*,49,65,76,97

Question type three (Hill sorting)

Example 3. Sort {50, 26, 38, 80, 70, 90, 8, 30, 40, 20}. The result is an increasing Hill sort. The selection of each increment is DK 1 =5, DK 2 respectively. =3 and DK 3 =1.

Hill sorting :
(1) The first pass of Hill sorting:
Insert image description here
the first pass, the result is { }; (2) The second and third pass of Hill sorting: the second pass, the result is { }; (3) The third pass , that is, the final result is { }. 50,8,30,40,20,90,26,38,80,70

Insert image description here
26,8,30,40,20,80,50,38,90,70
8,20,26,30,38,40,50,70,80,90

Question type four (bubble sort)

Example 4: For the initial sequence {46, 74, 53, 14, 26, 38, 86, 65, 27, 34}, the sorting result is increasing bubble sorting, and the sorting result of each sorting trip is written.

Bubble sorting :
(1) The first pass, 74>46, conforms to increment and does not conform to exchange, 53<74, does not conform to incremental exchange, the sequence is {46, 53, 74...}, 14<74, does not conform to incremental exchange, The sequence is {46, 53, 14, 74,...}, 26<74, which does not comply with incremental exchange. The sequence is {46, 53, 14, 26, 74,...}, 38 <74, which does not comply with incremental exchange. The sequence is {46, 53, 14, 26, 38, 74,...}, 86>74, which conforms to increment but not exchange, 65<86, which does not conform to increment exchange, and the sequence is {46, 53, 14, 26, 38, 74, 65, 86,...}, 27<86, does not comply with incremental exchange, the sequence is {46, 53, 14, 26, 38, 74, 65, 27, 86,...}, 34<86, does not comply with Incremental exchange, the sequence is {46, 53, 14, 26, 38, 74, 65, 27, 34, 86}, so the first pass result is {46, 53, 14, 26, 38, 74, 65, 27, 34, 86};
(2) The second pass, 53>46, conforms to the incremental exchange, 14<53, does not conform to the incremental exchange, the sequence is {46, 14, 53...}, 26<53, does not conform to the incremental exchange, The sequence is {46, 14, 26, 53,…}, 38<53, which does not conform to incremental exchange. The sequence is {46, 14, 26, 38, 53,…}, 74>53, which conforms to increment and does not conform to exchange. 65<74, does not conform to incremental exchange, the sequence is {46, 14, 26, 38, 53, 65, 74,...}, 27<74, does not conform to incremental exchange, the sequence is {46, 14, 26, 38, 53, 65, 27, 74,...}, 34<74, does not comply with incremental exchange, the sequence is {46, 14, 26, 38, 53, 65, 27, 34, 74}, 86>74, does not comply with incremental exchange Exchange, so the result of the second trip is {46, 14, 26, 38, 53, 65, 27, 34, 74,86};
(3) The third trip,..., so the result of the third trip is {14, 26, 38, 46, 53, 27, 34, <ai=7>};65,74,86
(4) The fourth trip,..., so the result of the fourth trip is {14, 26, 38, 46, 27, 34, 53,65,74,86};
(5) The fifth trip,..., so the result of the fifth trip is {14, 26, 38, 27, 34, 46,53,65,74,86};
(6) The sixth trip,..., so the result of the sixth trip is {14, 26, 27, 34, 38,46,53,65,74,86};
(7) The seventh trip,..., so the seventh The result of the trip is {14, 26, 27, 34, 38,46,53,65,74,86}. At this time, the entire sequence increases to the final result.

Question type five (quick sort)

Example 5: Perform quick sorting algorithm on a sequence {46, 79, 56, 38, 40, 84}, and write down the whole process of quick sorting from small to large with the first element as the pivot.

Quick sort :
(1) The first pass, with the first element 46 as the pivot, i and j point to the head and tail elements of the sequence, start the first pass of quick sort [Finally, elements smaller than the pivot will be exchanged to to the left, and elements larger than it will be swapped to the right]:
Insert image description here
The whole process ensures that the element to the left of the i pointer is smaller than the pivot element, and the element to the right of the j pointer is larger than the pivot element.
First, for j, search from right to left and find an element smaller than the pivot element. If found, j will stop (element 84 is larger than the pivot element, so there is no need to swap and move): put the
Insert image description here
element 40 pointed to by j at the position of i On the top, the original position of j is vacated, ensuring that the left side of the i pointer is an element smaller than the pivot element, and the right side of the j pointer is an element larger than the pivot element: Then for i, search from left to right to find an element larger than the pivot element
Insert image description here
. If the element of i is found, i will stop (element 40 is smaller than the pivot element, so there is no need to swap and move):
Insert image description here
Place the element 79 pointed to by i at the position of j, leaving the original position of i vacant, ensuring that the left side of the i pointer is smaller than the pivot element. The axis element is smaller. The right side of the j pointer is an element larger than the pivot element:
Insert image description here
continue searching for j from right to left, and find an element smaller than the pivot element. If found, j stops:
Insert image description here
move the element pointed to by j to 38 Place it at the position of i, and leave the original position of j. Ensure that the left side of the i pointer is an element smaller than the pivot element, and the right side of the j pointer is an element larger than the pivot element: Then for i, continue to search from left to right
Insert image description here
. , find an element that is larger than the pivot element. If found, i will stop:
Insert image description here
put the element 56 pointed to by i at the position of j, and leave the original position of i. Make sure that the left side of the i pointer is an element smaller than the pivot element, j The right side of the pointer is an element larger than the pivot element:
Insert image description here
then continue to search from right to left for j, and find an element smaller than the pivot element. If found, j stops (56 is greater than 46, so there is no need to exchange and move). At this time i and j meet:
Insert image description here
at this time i=j, this position is the final position of the pivot element, put the pivot element 46 at this position, and the first quick sort process ends:
Insert image description here
The sequence after the first pass of quick sort is { }; (2) In the second pass, continue to use the first element as the pivot element. At this time, 40 is the pivot, and i and j point to the head and tail elements of the sequence. Start Perform the second quick sort: For j, search from right to left and find an element smaller than the pivot element. If found, j stops: put the element 38 pointed to by j at the position of i, and the original position of j is empty. Out: Then for i, search from left to right to find an element larger than the pivot element. If found, i stops. At this time, i and j meet: at this time, i =j, this position is the final position of the pivot element. , place pivot element 40 at this position, and the second quick sort process ends: Since after two quick sort passes, the entire sequence is already in order, quick sort ends, and the final sequence result is: { }. 40,38,46,56,79,84

Insert image description here

Insert image description here

Insert image description here

Insert image description here

Insert image description here
38,40,46,56,79,84

Question type six (simple selection sorting)

Example 6: Perform simple selection sorting on the sequence {-2, 0, 7, 1, 4, 3} with increasing results, and write the sorting results of each sorting pass.

Simple selection sort :
(1) In the first pass, search for the smallest element from left to right, find -2, and exchange this element with the first element. Since -2 itself is at the first element position, no exchange has occurred. The sequence is { , 0, 7, 1, 4, 3}; (2) In the second pass, in the remaining unordered sequence, search for the smallest element from left to right, find 0, and combine this element with the second The elements are exchanged. Since 0 itself is in the second element position, no exchange occurs, and the sequence is { , 7, 1, 4, 3}; (3) The third pass, in the remaining unordered sequence, from left to Search for the smallest element on the right, find 1, exchange this element with the third element 7, the sequence is {, 7, 4, 3}; (4) The fourth pass, in the remaining unordered sequence, start from the left Search for the smallest element to the right, find 3, exchange this element with the fourth element 7, the sequence is {, 4, 7}; (5) The fifth pass, in the remaining unordered sequence, from left to Search for the smallest element on the right and find 4. No exchange has occurred, and the sequence is { , 7}; so the final result is { }. -2
Insert image description here
-2,0
Insert image description here
-2,0,1
Insert image description here
-2,0,1,3
Insert image description here
-2,0,1,3,4
Insert image description here
-2,0,1,3,4,7

Question Type 7 (Heap Sorting)

Example 7: The initial heap is {15, 21, 19, 32, 40, 29, 33, 38}, perform the heap sorting algorithm, and write down the entire process of each heap sorting from small to large.

Heap adjustment :
The initial heap tree is as follows:
Insert image description here
the available non-leaf node numbers i≤⌊N/2 ⌋=⌊8/2 ⌋=4, check whether all non-terminal nodes meet the requirements of the large root heap, that is, check i≤4 nodes and check them in order from bottom to top.
i=4, node 32 does not meet the requirements:
Insert image description here
Insert image description here
i=3, node 19 does not meet the requirements:
Insert image description here
Insert image description here
i=2, node 21 does not meet the requirements:
Insert image description here
Insert image description here
i=1, node 15 does not meet the requirements:
Insert image description here
Insert image description here
due to the above rounds After the exchange, it can be found that node 15 does not meet the requirements of the large root heap. Continue to adjust downward:
Insert image description here
still need to adjust:
Insert image description here
heap sorting :
(1) In the first pass, exchange the top element of the heap with the last element of the heap, and The top element is added to the ordered subsequence, that is, 40 and 15 are exchanged:
Insert image description here
Insert image description here
it can be seen that the sequence does not meet the requirements of the large root heap at this time (excluding the ordered subsequence 40), so the large root heap needs to be restored, and the remaining unordered sequence Adjusted to a large root heap:
Insert image description here
Insert image description here
The result of the first pass of heap sorting is {38, 32, 33, 15, 21, 29, 19, 40};
(2) The second pass, the operation is the same, the top element of the heap is combined with the last element of the heap The elements are exchanged, and the top element of the heap is added to the ordered subsequence, that is, 38 and 19 are exchanged: the
Insert image description here
remaining unordered sequence is adjusted into a large root heap:
Insert image description here
Insert image description here
the result of the second heap sorting is {33, 32, 29, 15, 21, 19, 38,40};
(3) In the third pass, 33 and 19 are exchanged:
Insert image description here
the remaining unordered sequence is adjusted to a large root heap:
Insert image description here
Insert image description here
the result of the third pass of heap sorting is {32, 21, 29, 15, 19, 33,38,40};
(4 ) The fourth trip, exchange of 32 and 19:
Insert image description here
The remaining disordered sequence is adjusted to a large root heap:
Insert image description here
the result of the fourth pass of heap sorting is {29, 21, 19, 15, 32,33,38,40};
(5) The fifth pass, 29 and 15 are exchanged:
Insert image description here
the remaining disordered sequence is adjusted to Big root heap:
Insert image description here
The result of the fifth heap sorting is {21, 15, 19, 29,32,33,38,40};
(6) The sixth pass, 21 and 19 are exchanged:
Insert image description here
the remaining unordered sequence is adjusted to the big root heap:
Insert image description here
The result of the sixth heap sorting is {15, 19, 21,29,32,33,38,40};
(7) The seventh pass, since it conforms to the large root heap, no exchange is needed:
Insert image description here
the result is {15, 19,21,29,32,33,38,40}
, leaving the last element, and it ends. The sequence obtained at this time is the final result:
Insert image description here
the seventh pass Heap sorting, that is, the final result is { }. 15,19,21,29,32,33,38,40

Question Type 8 (Merge and Sort)

Example 8: Given the sequence {34, 15, 13, 93, 65, 74, 20, 17}, perform an incremental two-way merge sort on it, and write the sorting results of each pass.

Two-way merge sort :
Two-way merge sort, k=2, and the number of elements is N=8. Since k m =N, that is, m=⌈log k N⌉, so m=3, three-way merge sort.
Divide the initial sequence into 8 subsequences containing only 1 element:
Insert image description here
(1) In the first merge, merge two by two to form several subsequences composed of two elements, and make all subsequences in increasing order:
Insert image description here
So the sequence result of the first pass is { , , , }. (2) In the second pass of merging, continue pairwise merging to form two subsequences composed of four elements: so the sequence result of the second pass is { , }. (3) The third pass of merging, and continuing to merge two by two, can form a complete ordered sequence: so the third pass, that is, the final sequence result is { }. 15,3413,9365,7417,20

Insert image description here
Insert image description here
13,15,34,9317,20,65,74

Insert image description here
13,15,17,20,34,65,74,93

Question type nine (radix sorting)

Example 9: Perform increasing radix sorting on the initial sequence {476, 513, 703, 189, 147, 577, 983, 521, 147*, 532}, and write the sorting results of each pass.

Radix sorting :
(1) First pass: For the ones digit,
Insert image description here
the first pass sequence can be obtained as { }; (2) Second pass: For the tens digit, the second pass sequence can be obtained as { }; (2) Second pass: For the hundreds digit , the third pass sequence can be obtained, that is, the final result is { }. 521,532,513,703,983,476,147,577,147*,189

Insert image description here
703、513、521、532、147、147*、476、577、983、189

Insert image description here
147、147*、189、476、513、521、532、577、703、983

Guess you like

Origin blog.csdn.net/qq_43085848/article/details/132639360