(6) Sorting algorithm: Hill sorting

First, the steps of Hill sorting

     1. Select an increment h and press h as the basis for grouping to group the data

     2. Complete the insertion sort for each group of data divided into groups

     3. Decrease the increment, the minimum is 1, repeat step 2

 

2. Selection of increment h

      Selection rules for the initial value of h:

      int h = 1;

    //Calculate the initial value of h, num is the number of elements in the array
    while (h <num / 2)
    {         h = 2 * h + 1;     }

    h's loop rule

    h = h/2;

 

3. Code and running results:

  


#include <iostream>

using namespace std;

void shell_sort(int arry[], int num)
{
	int h = 1;

	//计算h的初始值
	while (h < num / 2)
	{
		h = 2 * h + 1;
	}
	cout << "h=" << h << endl;

	while (h >= 1)
	{
		//每次分组,要插入的第一个元素的index 是h
		for (int i = h; i < num; i++)
		{
			//开始插入排序
			for (int j = i; j >= h; j -= h)
			{
				if (arry[j - h] > arry[j])
				{
					int tmp = arry[j - h];

					arry[j - h] = arry[j];
					arry[j] = tmp;
				}
			}
		}

		h = h / 2;
		cout << "h=" << h << endl;
	}


}


int main()
{
	int arr[] = {2,1,3,5,5,6,7,4,1};

	shell_sort(arr,sizeof(arr)/sizeof(arr[0]));

	for (int i = 0; i < (sizeof(arr) / sizeof(arr[0])); i++)
		cout << arr[i] << endl;


	return 0;
}


 operation result:

 

 

 

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/109389188