Hill sort and bucket sort of data structure

1. Hill sort

        First of all, we need to find the principle of Hill sorting.

        Hill sorting (shell): Shell sorting is to group the sequence according to 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 entire sequence is exactly grouped and the algorithm terminates.

        as the picture shows:

 so

void test_shell(int* a, int len)//希尔排序 
{
	int step = len / 2;		//步长
	int temp;				//用于储存临时待插数据
	int j;					//
	while (step)	//步长一直到0为止
	{
		for (int i = step; i < len; i++)//步长进行分组,组内进行插入
		{
			temp = a[i];//储存临时待插数据
			for (j = i - step; j >= 0 && a[j] > temp; j -= step)
			{
				a[j + step] = a[j];
			}
			a[j + step] = temp;
		}
		step /= 2;
	}
}

test:

 2. Bucket Sort

        Bucket sorting is also called box sorting. We need to determine the size and number of buckets, which are generally determined according to the value range of the elements to be sorted.

        For example, if I have 10 data and sort them by bucket, then we will make ten boxes from 0-9

As shown in the picture:

         Then the first step, what we want is ascending order, so we can divide by the number of digits, starting from the ones digit (if you want descending order, you can start from the hundreds digit).

        

 Then sort the tens again:

        

 Finally, if you sort by hundreds, you will find that, except for 132 in the 1 position, the others are all ordered in the 0 position

 The above is the principle of bucket sorting, so the code is as follows:

void tong_test(int* a, int len)
{
	int wei = 1;     //开始是个位
	int data_wei;    //用来存放位上面的数值
	int** p = new int* [10];    //创建十个箱子
	for (int i = 0; i < 10; i++)
	{
		p[i] = new int[len];    //每个箱子都有原数组的长度
	}
	while (wei < 1000)            //这个值是可以自己替换的,我这里没有大于千位的数,就写了1000
	{
		for (int i = 0; i < 10; i++)
		{
			for (int k = 0; k < len; k++)
			{
				p[i][k] = -1;    //这是对箱子内部数据的初始化,为-1
			}
		}
		for (int i = 0; i < len; i++)
		{
			data_wei = a[i] / wei % 10;    //对个,十,百位进行计算放在哪个箱子里面
			p[data_wei][i] = a[i];
		}
		int j = 0;
		for (int i = 0; i < 10; i++)
		{
			for (int k = 0; k < len; k++)
			{
				if (p[i][k] != -1)        //将放入箱子的数据重新存入数组里面
				{
					a[j++] = p[i][k];
				}
			}
		}
		wei *= 10;      //位数*10,从个位到十位,十位到百位等等
	}
}

result:

 

Guess you like

Origin blog.csdn.net/q244645787/article/details/126687751