`
urey
  • 浏览: 24942 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论
  • carmark: 做什么都好,自己喜欢就好,我是做Unix以及C和perl相关的 ...
    混沌。
  • urey: toeo 写道我大学 也是信息与计算科学的我现在是做java  ...
    混沌。
  • toeo: 我大学 也是信息与计算科学的我现在是做java  弄web.要 ...
    混沌。

Shell Sort

阅读更多
//header in use


#include <stdio.h>
#include <tchar.h>

#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;

#define MAX 20
int _tmain(int argc, _TCHAR* argv[])
{
	int shellbox[MAX];
	void shellsort(int *, int);
	srand(time(NULL));						//using rand() and time() to build ramdom number vector
	for(int i = 0; i != MAX; i++)
	{
		shellbox[i] = rand() % 1000;
		cout<<shellbox[i]<<' ';
	}
	shellsort(shellbox, MAX);
	cout << endl;
	for(int i = 0; i != MAX; i++)
	{
		cout<<shellbox[i]<<' ';
	}
	
	return 0;
}
void shellsort(int *shell, int max)
{
	int n = (int)max/2;
	int length = 0;											//small vector length in all shell box
	int end = 0;
	int temp;
	while(!(n==0)){											// shell sort start
		length=n*int((max - 1)/n);
///////////////////////////////////////////////////////////////////
		for(int i = 0; i != n; i++){
			end = i +length;
			for(int j = end; j > 0;){
	/////////////////////////////////////////////////////////////////// sort from i to end
				for(int c = i; c < j;){							// c is the change, i is the start, j is the end
					if(shell[c] > shell[c+n]){
						temp = shell[c];
						shell[c] = shell[c+n];
						shell[c+n] = temp;
					}
					c = c +n;
				}
	///////////////////////////////////////////////////////////////////
				j = j - n;
			}
		}
///////////////////////////////////////////////////////////////////
		n=int(n/2);
	}
	return;
}

 

自己实现的shell排序,底层排序用的是冒泡法。

 

the shell sort from Data Srtuctures and Algorithm Analysis in C++

       /**
         * Shellsort, using Shell's (poor) increments.
         */
        template <class Comparable>
        void shellsort( vector<Comparable> & a )
        {
            for( int gap = a.size( ) / 2; gap > 0; gap /= 2 )
                for( int i = gap; i < a.size( ); i++ )
                {
                    Comparable tmp = a[ i ];
                    int j = i;
                    for( ; j >= gap && tmp < a[ j - gap ]; j -= gap )
                        a[ j ] = a[ j - gap ];
                    a[ j ] = tmp;
                }
        }
 


 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics