데이터 구조 몇 가지 삽입 정렬

#include <iostream>


using namespace std;


void direct_sort(int a[], int len)
{
	int i, j;
	for(i=2; i<=len; i++)
	{
		a[0] = a[i];
		j = i-1;
		while(a[0] < a[j])
		{
			//        j+1
			a[j+1] = a[j];
			j--;
		}
		a[j+1] = a[0];
	}


	cout<<"      :";
	for(i=1; i<len; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}


void half_insert_sort(int a[], int len)
{
	int i, j, low, high, mid;
	for(i=2; i<=len; i++)
	{
		a[0] = a[i];
		low = 1;
		high = i - 1;
		while(low <= high)
		{
			//        high+1
			mid = (low+high)/2;
			if(a[0] > a[mid])
				low = mid + 1;
			else
				high = mid - 1;
		}
		for(j=i-1; j>=high+1; j--)
			a[j+1] = a[j];
		a[high+1] = a[0];
	}


	cout<<"      :";
	for(i=1; i<len; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}


void shell_sort(int a[], int len)
{
	int d = len/2;
	int i, j, temp;
	while(d > 0)
	{
		for(i=d; i<len; i++)
		{
			j = i - d;
			while(j >= 0)
			{
				if(a[j] > a[j+d])
				{
					temp = a[j];
					a[j] = a[j+1];
					a[j+1] = temp;
					j = j - d;
				}
				else
					j = -1;
			}
		}
		d = d/2;
	}


	cout<<"    :";
	for(i=0; i<len; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}


int main(void)
{
	int a[] = {9, 4, 6, 1, 8, 3, 2};
	int len = sizeof(a)/sizeof(int);


	//    ,a[0]      
//	direct_sort(a, len);


	//      ,a[0]      
//	half_insert_sort(a, len);


	//    
	shell_sort(a, len);
	return 0;
}

좋은 웹페이지 즐겨찾기