[C++ implements insertion sort, Hill sort, bubble sort, quick sort, selection sort]

Use C++ to implement insertion sorting, Hill sorting, bubble sorting, quick sorting, and selection sorting algorithms.

1. Insertion sort

Insertion sorting is also generally called direct insertion sorting. It is an efficient algorithm for sorting a small number of elements. Insertion sorting is the simplest sorting method. Its basic idea is to insert a record into the sorted ordered list to generate a new ordered list with the number of records increased by 1. In the implementation process, a double-layer loop is used. The outer loop searches for all elements except the first element, and the inner loop searches for the position to be inserted in the ordered list in front of the current element and moves it.

Insertion sort works like many people sort a hand of poker. We start with an empty left hand and the cards face down on the table. Then, we take one card from the table at a time and insert it in the correct position in the left hand. To find the correct position of a card, we compare it with every card already in the hand, from right to left. The cards held in the left hand are always sorted, and it turns out that these cards are the top cards in the pile on the table.

Insertion sorting means that among the elements to be sorted, assuming that the previous n-1 (where n>=2) numbers are already in order, now insert the nth number into the previously arranged sequence, and then find Suitable for your own position, so that the sequence inserted into the nth number is also in order. According to this method, all elements are inserted until the entire sequence is sorted, which is called insertion sort.

#include<iostream>
using namespace std;

int main()
{
    
    
	int arr[6]={
    
    9,7,6,5,4,3};
	//遍历数组,依次进行比较 
	for(int i=0;i<5;i++){
    
    
		/*
		比较i和i+1,如果升序排序,则判断第i个元素是否大于第i+1个
		元素,如果是,则将第i+1个元素依次与之前的所有元素进行比较并
		排序,完成后将第i个元素插入到第i+1个元素的位置上。降序也是
		同样的原理。 
		*/ 
		if(arr[i]>arr[i+1]){
    
    
			//交换
			//从第i个元素开始交换 
			int j=i;
			//将需要插入的元素使用变量temp保存 
			int temp=arr[i+1];
			/**
			将第i个元素之前的所有元素进行一次重新排序,保证第0-i个元素
			之间是排好序的。 
			*/ 
			while(j>=0&&temp<arr[j]){
    
    
				arr[j+1]=arr[j];
				j--;
			}
			arr[j+1]=temp;
		}
	}
	//打印输出排序结果 
	for(int i=0;i<6;i++){
    
    
		cout<<arr[i]<<" ";
	}
 } 

2. Hill sort

Shell's Sort is a kind of insertion sort, also known as "Diminishing Increment Sort", which is a more efficient and improved version of the direct insertion sort algorithm. Hill sort is an unstable sorting algorithm. This method is named after DLShell proposed in 1959.

Hill sorting is to group the records by a certain increment of the subscript, and use the direct insertion sorting algorithm to sort each group; as the increment gradually decreases, each group contains more and more keywords. When the increment is reduced to 1, The algorithm terminates when the entire file has just been grouped.

#include<iostream>
using namespace std;

int main()
{
    
    
	int arr[6]={
    
    9,7,6,5,4,3};
	//控制步长 
	for(int gap=6/2;gap>0;gap/=2){
    
    
		//遍历所有的组 
		for(int i=0;i<gap;i++){
    
    
			//遍历每个组中的所有元素 
			for(int j=i-gap;j>=0;j-=gap){
    
    
				/*
				比较第j个元素和第j+gap个元素,不满足排序规则的交换
				元素顺序。 
				*/ 
				if(arr[j]>arr[j+gap]){
    
    
					int t=arr[j];
					arr[j]=arr[j+gap];
					arr[j+gap]=t;
				}
			}
		}
	} 
	//打印输出排序结果 
	for(int i=0;i<6;i++){
    
    
		cout<<arr[i]<<" ";
	}
 } 

3. Bubble sort

Bubble Sort is a relatively simple sorting algorithm in the field of computer science.

It repeatedly visits the column of elements to be sorted, compares two adjacent elements in turn, and exchanges them if the order (such as from large to small, initial letter from Z to A) is wrong. The work of visiting elements is repeated until no adjacent elements need to be exchanged, that is to say, the element column has been sorted.

The name of this algorithm comes from the fact that the smaller elements will slowly "float" to the top of the sequence (in ascending or descending order) through exchange, just like the bubbles of carbon dioxide in carbonated drinks will eventually float to the top, hence the name "bubbling". Sort".

The principle of the bubble sort algorithm is as follows:

  1. Compare adjacent elements. If the first is bigger than the second, swap them both.
  2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
  3. Repeat the above steps for all elements except the last one.
  4. Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.
#include <iostream>
using namespace std;

int main()
{
    
    
    int array[8] = {
    
    8,7,6,5,4,3,2,1};
    //打印输出排序前的数组 
    cout<<"排序前的数组为:";
    for (int i = 0; i < 8; i++){
    
    
        cout<<array[i]<<" ";
    }
    //冒泡排序 
    for(int i=0;i<8;i++){
    
    
    	for(int j=0;j<8-1-i;j++){
    
     
    		if(array[j]>array[j+1]){
    
    
    			int temp=array[j];
    			array[j]=array[j+1];
    			array[j+1]=temp;
			}
		}
	}
    //打印输出排序后的数组 
    cout<<"\n排序后的数组为:";
    for (int i = 0; i < 8; i++){
    
    
        cout<<array[i]<<" ";
    }
    
    return 0;
}

4. Quick Sort

The quick sort algorithm implements sorting through multiple comparisons and exchanges, and its sorting process is as follows:

(1) First, set a cutoff value, and divide the array into left and right parts through the cutoff value.

(2) Collect the data greater than or equal to the cutoff value to the right of the array, and collect the data smaller than the cutoff value to the left of the array. At this time, each element in the left part is smaller than the cutoff value, and each element in the right part is greater than or equal to the cutoff value.

(3) Then, the left and right data can be sorted independently. For the array data on the left side, a boundary value can be taken to divide this part of the data into left and right parts, and the smaller value is placed on the left side, and the larger value is placed on the right side. The array data on the right can also be processed similarly.

(4) Repeat the above process, it can be seen that this is a recursive definition. After sorting the left part by recursion, recursively sort the order of the right part. When the sorting of the data in the left and right parts is completed, the sorting of the entire array is also completed.
principle

Assuming that the array to be sorted is A[0]...A[N-1], first randomly select a data (usually the first number of the array) as the key data, and then put all the numbers smaller than it into it On the left, all numbers larger than it are placed on the right. This process is called a quick sort. It is worth noting that quicksort is not a stable sorting algorithm, that is, the relative positions of multiple identical values ​​may change at the end of the algorithm.

The algorithm for one-pass quick sort is:

1) Set two variables i, j, when sorting starts: i=0, j=N-1;

2) Assign the first array element as the key data to key , that is, key = A[0];

3) Search forward from j, that is, search forward from the back (j–), find the first value A[j] smaller than the key , and exchange the values ​​​​of A[j] and A[i];

4) Search backward from i, that is, search backward from the front (i++), find the first A[i] greater than the key , and exchange the values ​​​​of A[i] and A[j];

5) Repeat steps 3 and 4 until ij; In steps 3 and 4, no qualified value is found, that is, when A[j] in 3 is not less than key , and A[i] in 4 is not greater than key , change the values ​​of j and i so that j=j-1 , i=i+1, until found. Find a value that meets the conditions, and when the exchange is performed, the positions of the i and j pointers remain unchanged. In addition, iThe process of j must be exactly when i++ or j– is completed, and the cycle ends at this time.

Sort Demo

Suppose the initial sequence {xi} is: 5, 3, 7, 6, 4, 1, 0, 2, 9, 10, 8.

At this time, ref=5, i=1, j=11, looking from the back to the front, the first number smaller than 5 is x8=2, so the sequence is: 2, 3, 7, 6, 4, 1, 0, 5, 9, 10, 8.

At this time i=1, j=8, look from front to back, the first number greater than 5 is x3=7, so the sequence is: 2, 3, 5, 6, 4, 1, 0, 7, 9, 10, 8.

At this time, i=3, j=8, look forward from the 8th digit, the first number smaller than 5 is x7=0, so: 2, 3, 0, 6, 4, 1, 5, 7, 9, 10, 8.

At this time, i=3, j=7, look from the 3rd place, the first number greater than 5 is x4=6, so: 2, 3, 0, 5, 4, 1, 6, 7, 9, 10, 8.

At this time, i=4, j=7, look forward from the 7th digit, the first number smaller than 5 is x6=1, so: 2, 3, 0, 1, 4, 5, 6, 7, 9, 10, 8.

At this time, i=4, j=6, search from the 4th place, until the 6th place, there is a number larger than 5, at this time, i=j=6, ref becomes a dividing line, the number before it are smaller than it, and the subsequent numbers are larger than it. For the two parts before and after, the same method can be used to sort.

#include <iostream>
 
using namespace std;
 
void Qsort(int arr[], int low, int high){
    
    
    if (high <= low){
    
    
    	return;
	}
	
    int left = low;
    int right = high;
    int key = arr[low];
    
    while (true)
    {
    
    
        //将比key小的值放key左边,比key大的值放key右边 
		/*从左向右找比key大的值*/
        while (arr[left] <= key)
        {
    
    
            left++;//从左往右,下标递增 
            //当遍历到最后一个元素时,结束循环 
            if (left == high){
    
    
                break;
            }
        }
        /*从右向左找比key小的值*/
        while (arr[right] >= key)
        {
    
    
            right--; //从右往左,下标递减 
            //当遍历到第一个元素时,结束循环 
			if (right == low){
    
    
                break;
            }
        }
//        cout<<"left:"<<left<<" right:"<<right<<"\n"; 
        /*
		当比key小的数全在左边,比key大的数全在右边时,表
		示第一次排序完成,结束循环
		*/ 
		if (left >= right){
    
    
        	break;
		}
        /*
		将比key小的数移到左边,比key大的数移到右边,
		交换left,right对应的值
		*/
        int temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
    }
    /*分别对左右两边的数字进行排序,
	中枢值与right对应值交换*/
    arr[low] = arr[right];
    arr[right] = key;
    Qsort(arr, low, right - 1);
    Qsort(arr, right + 1, high);
}
 
int main()
{
    
    
    int arr[] = {
    
    52, 64, 59, 52, 75, 28, 98, 30, 25};
    //获取数组长度 
	int len = sizeof(arr)/sizeof(arr[0]); 
	//打印排序前的数组
	cout<<"排序前:"; 
    for(int i = 0; i < len; i++)
    {
    
    
        cout << arr[i] << " ";
    }
    //调用快速排序函数 
	Qsort(arr, 0, len- 1);
	//打印排序后的数组 
    cout<<"\n排序后:";
    for(int i = 0; i < len; i++)
    {
    
    
        cout << arr[i] << " ";
    }
    return 0;
}

Five, selection sort

Selection sort is a simple and intuitive sorting algorithm. Its working principle is: select the smallest (or largest) element from the data elements to be sorted for the first time, store it in the starting position of the sequence, and then find the smallest (largest) element from the remaining unsorted elements element and put it at the end of the sorted sequence. And so on, until the number of all data elements to be sorted is zero. Selection sort is an unstable sorting method.

Sorting idea : first find the smallest (largest) element in the unsorted sequence, store it at the beginning of the sorted sequence, then continue to find the smallest (largest) element from the remaining unsorted elements, and then put it at the end of the sorted sequence . And so on until all elements are sorted.

The specific implementation method :

①Initial state: The unordered area is R[0…n-1] (a total of n elements), and the ordered area is empty.

② The first sorting

Set a variable i, let i cycle from 0 to n-2, compare the size of element i and element i+1 in the array, if R[i+1] is smaller than R[i], use a variable k To remember his position (ie k=i+1). By the end of the loop, we should have found the position of the smallest number in R. Then make a judgment, if the smallest element is not the first element of R, let the first element exchange values ​​with him, so that R[0...0] and R[1...n-1] become records respectively A new ordered area whose number is increased by 1 and a new disordered area whose number of records is decreased by 1.

……

③Sorting for the i-th trip

When the i-th sorting starts, the current ordered area and unordered area are R[0...i-1] and R[i...n-1] respectively. This sorting selects the record R[k] with the smallest key from the current unordered area, and exchanges it with the first record R in the unordered area, so that R[0...i] and R become the number of records respectively A new ordered area with an increase of 1 and a new disordered area with a decrease in the number of records.

Figure 1 example: (selection sort by finding the minimum value)

Figure 1 Selection sort (minimum value) example

#include<iostream>

using namespace std;

/*遍历寻找当前序列中的最小值,返回最小值的下标*/
int selectMin(int arr[],int i,int len){
    
    
	int min=i;
	for(;i<len;i++){
    
    
		if(arr[i]<arr[min]){
    
    
			min=i;
		}
	}
	return min;
}

int main()
{
    
    
	int arr[]={
    
    5,8,2,4,1,6};
	int len=sizeof(arr)/sizeof(arr[0]);
	for(int i=0;i<len;i++){
    
    
        //接收当前序列的最小值下标
		int j=selectMin(arr,i,len);
		//判断最小值是否为当前元素,如果不是,则交换最小值和当前元素的位置
        if(i!=j){
    
    
			int temp=arr[i];
			arr[i]=arr[j];
			arr[j]=temp;
		}
	}
	for(int i=0;i<len;i++){
    
    
		cout<<arr[i]<<" ";
	}
  }  

Guess you like

Origin blog.csdn.net/qq_43884946/article/details/130883709