數據結構中的排序--希爾(shell)排序

shell排序是插入排序的優化,當需要排序的數據量比較大的時候,比較有幫助。

shell排序是一種分組排序,所以重點不同在於分組。如分組的大小初始值爲長度的一般,每次分組的大小爲之前的一般,直到爲1.

原始數列         5 3 7 4 3 9 6 2 10 4 3 7 1      長度13

第一次分組6   5                6                  1

                       1                5                  6

                          3                 2

                          2                 3

                             7                  10

                             7                   10

                                4                    4

                                4                    4

                                   3                    3

                                   3                     3

                                      9                   7

                                      7                   9

將上面的紅色的數字按照下面截圖所示的順序就是第一次分組的排序了。

                                          

              排好序後:1 2 7 4 3 7 5 3 10 4 3 9 6

下面的就依次類推。

第二次分組3   1 2 7 4 3 7 5 3 10 4 3 9 6

                       1       4       5         4       6

                          2       3       3         3      

                             7       7        10       9

     排好序後:1 2 7 4 3 7 4 3 9 5 3 10 6

第三次分組1   1 2 7 4 3 7 5 3 10 4 3 9 6

                      此時直接使用插入排序即可。

     排好序後:1 2 3 3 3 4 4 5 6 7 7 9 10

完整的測試程序:

#include "stdafx.h"
#include <iostream>
using namespace std;

void shell_ascending_sort(int data[], int n)
{
	int i = 0, j = 0, temp = 0, d = 0;

	for (i = n/2; i > 0; i = i/2)//控制增量,每次增量都減少一半
	{
		for (j = i; j < n; j++)
		{

			temp = data[j];
			for (d = j - i; d >= 0 && temp < data[d]; d-=i)
			{
				data[d + i] = data[d];
			}
			data[d + i] = temp;
		}
	}
}


void shell_desending_sort(int data[], int n)
{
	int i = 0, j = 0, temp = 0, d = 0;

	for (i = n / 2; i > 0; i = i / 2)//控制增量,每次增量都減少一半
	{
		for (j = i; j < n; j++)
		{

			temp = data[j];
			for (d = j - i; d >= 0 && temp > data[d]; d -= i)
			{
				data[d + i] = data[d];
			}
			data[d + i] = temp;
		}
	}
}

void print(int data[], int n)
{
	for (int i = 0; i < n; i++)
	{
		cout << data[i] << " ";
	}
	cout << endl;
}
int main()
{
	int num[] = {5,3, 7,4,3,9,6,2,10,4,3,7,1};
	int len = sizeof(num) / sizeof(int);

	cout << "data count:"<< len << ".  before sort: ";
	print(num, len);

	shell_ascending_sort(num, len);
	cout << "after sort: ";
	print(num, len);

	shell_desending_sort(num, len);
	cout << "after desending sort: ";
	print(num, len);

	return 0;
}

測試結果:

data count:13.  before sort: 5 3 7 4 3 9 6 2 10 4 3 7 1
6 :1 2 7 4 3 7 5 3 10 4 3 9 6
3 :1 2 7 4 3 7 4 3 9 5 3 10 6
1 :1 2 3 3 3 4 4 5 6 7 7 9 10
after sort: 1 2 3 3 3 4 4 5 6 7 7 9 10
6 :10 5 6 7 7 9 4 2 3 3 3 4 1
3 :10 7 9 7 5 6 4 3 4 3 2 3 1
1 :10 9 7 7 6 5 4 4 3 3 3 2 1
after desending sort: 10 9 7 7 6 5 4 4 3 3 3 2 1
請按任意鍵繼續. . .

發佈了236 篇原創文章 · 獲贊 39 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章