Simplest insert sort: thought, comparison between 22, Time complexity O (n^2)
voidBubblesort (vector<int>&vec,intN) { if(&vec==NULL)return; inttemp; BOOLFlag; for(inti =0; I < n-1; i++)//Outer loop control cycle times{flag=false;//a sign of whether or not to determine order for(intj =0; J < N-1I J + +)//Inner loop control boundary { if(Vec[j]>vec[j +1]) {temp=Vec[j]; VEC[J]= Vec[j +1]; Vec[j+1] =temp; Flag=true; } } if(!flag) Break; } }
2. Select Sort, thought: Assume that the first element of each cycle is the maximum value, and then pick the most value from the element that is not sorted later, and swap it.
voidSelectsort (vector<int>&vec,intN) { if(&vec = =NULL)return; intkey; intmin; inttemp; for(inti =0; I < n-1; i++)//outer control cycle times{Key=Vec[i]; Min=i; for(intj = i +1; J < N; J + +)//boundary of inner control loop { if(Vec[j] <key) {min= J;//index value that records the minimum valuekey = Vec[j];//Record Minimum value } } if(min! = i)//If there is a change, the Exchange{Temp=Vec[i]; Vec[i]=Vec[min]; Vec[min]=temp; } } }
3. Insert sort, thought: Each time the collection is never sorted, take an element into the already sorted array, notice the difference between using the array and judging the condition with the vector
voidInsertsort (vector<int>&vec,intN//The reference must be passed here, because this is a class object, unlike an array{ if(&vec = =NULL)return; intkey; for(inti =1; I < n; i++) {Key= Vec[i];//staging the value to insert intj = i;//staging the subscript to insert while(j>0&&key < Vec[j-1])//Note: Changing to while (KEY<VEC[J-1]&&J>0) is an error, and if the array is not a problem, because the vector check is more stringent, more secure, do not allow the appearance of vec[-1] (subscript out of bounds).{Vec[j]= Vec[j-1];//Move backward Onej--; } if(I!=J)//If there is a change in the subscript, it indicates that the insertion position has changed and needs to be reinsertedVEC[J] =key; }}
Bubble sort in C + +, select Sort, insert sort