Hill (shell) sort __ Hill Shell sort

Source: Internet
Author: User

The average time complexity of hill sort is O (nlog2n), Space complexity is O (1), time performance between O (n^2) and O (nlog2n). Hill sort is an unstable sort method whose performance can be fully played in the number of records to be sorted.

The basic idea of hill sorting: First, the whole sequence of sorted records is divided into several sub sequences, in the subsequence, the direct insertion sort is carried out, while the whole sequence is in order, then the whole record is inserted into the sequence directly, because in the direct insertion sort, the key word in the sorted record is very efficient.

Hill sort needs to solve two problems: first, how to split with the sorting record; second, how to sort the direct access in the subsequence. The following code is detailed.

Hill sort
#include <iostream>
using namespace std;
void Shellsort (int a[],int n) {
	int gap;
	for (gap=n/2;gap>0;gap/=2) {    //calculate each step for
		(int i=gap;i<n;i++) {   //start from the element of Gap, Each element is directly inserted into a sort
			if (A[i]<a[i-gap]) {
				int temp=a[i] with the data within its own group;
				for (int j=i-gap; (j>=0) && (Temp<a[j]); j-=gap) a[j+gap]=a[j];
				A[j+gap]=temp
			}
		}
		cout<< "before sort:";
		for (int k=0;k<10;k++)
			cout<<a[k]<< "";
		cout<<endl;
	}
}
void Main () {
	int a[10]={2,6,1,10,9,3,0,100,-1,7};
	Shellsort (a,10);
	cout<< "after sort:";
	for (int i=0;i<10;i++)
		cout<<a[i]<< "";
	cout<<endl;
}

The results of the operation are as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.