catalogue
- Select sort
- Insert sort
- Implementation of sort in STL
- data
- harvest
In this article, we will learn and practice the selection sorting and insertion sorting, and then analyze the implementation of the sorting algorithm in the STL of CPP to end the phase of the sorting algorithm.
1、 Select sort
- Suppose that the array content value corresponding to a subscript is the minimum value (generally the first undetermined value is used), and then use this value to compare the size with all subsequent values. If the latter value is less than this value, first record the position and value of the minimum value, and then compare the subsequent values. After a loop traversal, the minimum value changes greatly compared with the initial minimum value, Exchange if any.
- Add 1 to the subscript and repeat the first step
The implementation is relatively simple. We don’t draw pictures and analyze them. Detailed comments are added to the code
#include <iostream>
#include<array>
#include<algorithm>
using namespace std;
void printSortArray(int myarray[],int size){
for(int k=0; k<size; k++)
{
cout<<myarray[k]<<" ";
}
cout<<endl;
}
void swap(int *a,int i,int j)
{
int tmp = a[i];
a[i] = a[j];
a[j]=tmp;
}
void selectSort(int *a,int length)
{
for(int i = 0;i<length;i++)
{
//First, assume that the first element is the minimum value and traverse the record externally
int min = a[i];
int minPos = i;
for(int j =i+1;j<length;j++)
{
//Conduct a round of comparison with the minimum value assumed above. If the subsequent value is smaller than the assumed minimum value, assign the value to the minimum value,
if(min>a[j])
{
min =a[j];
minPos = j;
}
}
//After a round of comparison, check whether the subscript of the minimum value changes. If so, exchange it
if(i !=minPos)
{
swap(a,i,minPos);
}
//After one round, the rightmost pit is used only by the minimum value of the current wheel, and then the value of subsequent pit is determined by recirculation
}
}
int main(void) {
//Using a one bit array to represent a complete binary tree, its parent node and its left and right child nodes can be obtained from any node
int myarray[] ={6,7,1,2,10,5,8,3,4};
int size = sizeof(myarray)/sizeof(myarray[0]) ;
cout<<"size="<<size<<endl;
selectSort(myarray,size);
printSortArray(myarray,size);
return 0;
}
When you see the selection sort, it’s easy to think of the bubble sort we learned and practiced earlier. What’s the difference between them?
Bubble sorting is a comparison between two adjacent pairs. Each comparison may trigger interaction. Bubble sorting is to find the position by counting.
Selecting sorting is to assume that one is the minimum value, then compare the size with all the following contents one by one, and exchange once in each round. To select sorting, first determine the location and then find the value.
Their advantages are relatively simple, but their disadvantages are also obvious. The time complexity is O (n ^ 2). Selective sorting will also destroy the stability of the original order (that is, when there are the same values, the sequence before and after sorting the same values by selection will be destroyed).
2、 Insert sort
Insertion sorting is like when we play cards, the cards in our hands have been sorted. Start a new card and insert it into the appropriate position in the existing ordered cards. In order to make room for the elements to be inserted, we need to move the other elements larger than the value to be inserted to the right before insertion.
Insert a suitable application scenario: it is very efficient to insert non random (i.e. ordered) queues.
Let’s start the insertion sorting process step by step by drawing

The implementation is as follows
#include <iostream>
#include<array>
#include<algorithm>
using namespace std;
void printSortArray(int myarray[],int size){
for(int k=0; k<size; k++)
{
cout<<myarray[k]<<" ";
}
cout<<endl;
}
void swap(int *a,int i,int j)
{
int tmp = a[i];
a[i] = a[j];
a[j]=tmp;
}
void insertSort(int *a,int length)
{
//The array subscript starts at 1 and is compared with the previous value
int i,j,tmp;
for(i=1;i<length;i++){
int tmp= a[i];
for (j = i-1; j>=0; j--)
{
//If the following is less than the value of a position in the previous sequence table, move the value of the current bit backward by one bit and cycle in turn
if(tmp< a[j]){
a[j+1] = a[j];
} else {
break;
}
}
//After jumping out of the loop, assign TMP to the place to be inserted
a[j+1] = tmp;
}
}
int main(void) {
//Using a one bit array to represent a complete binary tree, its parent node and its left and right child nodes can be obtained from any node
int myarray[] ={6,7,1,2,10,5,8,3,4};
int size = sizeof(myarray)/sizeof(myarray[0]) ;
cout<<"size="<<size<<endl;
insertSort(myarray,size);
printSortArray(myarray,size);
return 0;
}
3、 Implementation of sorting algorithm in STL
Through these four articles on sorting algorithms, we understand the principle and implementation of basic selection sorting, insertion sorting, bubble sorting, quick sorting and heap sorting. Next, let’s look at the specific implementation of STL sorting algorithm in CPP
[source address]:https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a01347.html
template<typename _RandomAccessIterator>
05206 inline void
05207 sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
05208 {
05209 typedef typename iterator_traits<_RandomAccessIterator>::value_type
05210 _ValueType;
05211
05212 // concept requirements
05213 __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept<
05214 _RandomAccessIterator>)
05215 __glibcxx_function_requires(_LessThanComparableConcept<_ValueType>)
05216 __glibcxx_requires_valid_range(__first, __last);
05217
05218 if (__first != __last)
05219 {
05220 std::__introsort_loop(__first, __last,
05221 std::__lg(__last - __first) * 2);
05222 std::__final_insertion_sort(__first, __last);
05223 }
05224 }
__ LG function calculates the recursion depth to control the deterioration of segmentation. When the recursion depth reaches this value, heap sorting is used instead, because the time complexity of heap sorting is constant as nlogn
/// This is a helper function for the sort routines. Precondition: __n > 0.
02308 template<typename _Size>
02309 inline _Size
02310 __lg(_Size __n)
02311 {
02312 _Size __k;
02313 for (__k = 0; __n != 0; __n >>= 1)
02314 ++__k;
02315 return __k - 1;
02316 }
The implementation of quick sort is as follows:
02242 /// This is a helper function for the sort routine.
02243 template<typename _RandomAccessIterator, typename _Size>
02244 void
02245 __introsort_loop(_RandomAccessIterator __first,
02246 _RandomAccessIterator __last,
02247 _Size __depth_limit)
02248 {
02249 typedef typename iterator_traits<_RandomAccessIterator>::value_type
02250 _ValueType;
02251
//The number of intervals is greater than_ S_ Threshold uses quick sort
02252 while (__last - __first > int(_S_threshold))
02253 {
//If the specified recursion depth is reached, use heap sort instead
02254 if (__depth_limit == 0)
02255 {
02256 _GLIBCXX_STD_P::partial_sort(__first, __last, __last);
02257 return;
02258 }
02259 --__depth_limit;
02260 _RandomAccessIterator __cut =
02261 std::__unguarded_partition(__first, __last,
02262 _ValueType(std::__median(*__first,
02263 *(__first
02264 + (__last
02265 - __first)
02266 / 2),
02267 *(__last
02268 - 1))));
02269 std::__introsort_loop(__cut, __last, __depth_limit);
02270 __last = __cut;
02271 }
02272 }
Implementation of insertion sorting part:
/// This is a helper function for the sort routine.
02171 template<typename _RandomAccessIterator>
02172 void
02173 __final_insertion_sort(_RandomAccessIterator __first,
02174 _RandomAccessIterator __last)
02175 {
02176 if (__last - __first > int(_S_threshold))
02177 {
02178 std::__insertion_sort(__first, __first + int(_S_threshold));
02179 std::__unguarded_insertion_sort(__first + int(_S_threshold), __last);
02180 }
02181 else
02182 std::__insertion_sort(__first, __last);
02183 }
02093 /// This is a helper function for the sort routine.
02094 template<typename _RandomAccessIterator>
02095 void
02096 __insertion_sort(_RandomAccessIterator __first,
02097 _RandomAccessIterator __last)
02098 {
02099 if (__first == __last)
02100 return;
02101
02102 for (_RandomAccessIterator __i = __first + 1; __i != __last; ++__i)
02103 {
02104 typename iterator_traits<_RandomAccessIterator>::value_type
02105 __val = *__i;
02106 if (__val < *__first)
02107 {
02108 std::copy_backward(__first, __i, __i + 1);
02109 *__first = __val;
02110 }
02111 else
02112 std::__unguarded_linear_insert(__i, __val);
02113 }
02114 }

Image source: [C + + a deep pit interview question: what sort algorithm is used for the sort algorithm in STL?]:https://blog.csdn.net/qq_35440678/article/details/80147601
4、 Information
Algorithm
[difference between bubble sort and selection sort]:https://blog.csdn.net/weixin_41887155/article/details/85799820
[detailed explanation of sorting algorithm (I) direct insertion sorting]:https://www.bilibili.com/video/BV1Jv41167eL?from=search&seid=385501809024223768
[C + + a deep pit interview question: what sort algorithm is used for the sort algorithm in STL?]:https://blog.csdn.net/qq_35440678/article/details/80147601
5、 Harvest
- Understand and implement selection sorting and insertion sorting
- Understand the reason why sort uses quick sort, heap sort and insert sort in STL and the code implementation
There are many other types of sorting algorithms, such as Hill sorting, merge sorting, bucket sorting, etc. we don’t do learning and practice at this stage, and continue as needed.
Thank you for reading
Sorting algorithm is part of this article. Next we begin to enter the learning practice of query algorithm. Welcome to pay attention to the official account of “audio and video development trip” and learn and grow together.
Welcome to communicate