各種排序算法

#include<iostream>
using namespace std;

#define MAXSIZE 10
//1.冒泡排序
void bubble_sort(int a[],int n)
{
	for(int i=0;i<n-1;i++)
	{
		for(int j=i;j<n;j++)
		{
			if(a[i]>a[j])
				swap(a[i],a[j]);
		}
	}
}


//2.選擇排序
void select_sort(int a[],int n)
{
	int min;
	for(int i=0;i<n-1;i++)
	{
		min=i;
		for(int j=i;j<n;j++)
		{
			if(a[j]<a[min])
				min=j;
		}
		if(min!=i)
			swap(a[i],a[min]);
	}
}


//3.插入排序
void insert_sort(int a[],int n)
{
	for(int i=1;i<n;i++)
	{
		int temp=a[i];
		int j=i;
		while(j-1>=0&&temp<a[j-1])
		{
			a[j]=a[j-1];
			j--;
		}
		a[j]=temp;
	}
}



//4.希爾排序(插入排序的改進算法)
void shell_sort(int a[],int n)
{
	int gap=n;
	do{
		gap=gap/3+1;
		for(int i=gap;i<n;i+=gap)
		{
			int temp=a[i];
			int j=i;
			while(j-gap>=0&&temp<a[j-gap])
			{
				a[j]=a[j-gap];
				j-=gap;
			}
			a[j]=temp;
		}
	}while(gap>1);
	
}



//該調整的作用是把最大值與父節點交換
<pre name="code" class="cpp">void heapAdjust(int a[],int s,int size)
{
	int temp=a[s];
	int j=s;
	for(int i=2*s+1;i<=size;i=2*i+1)
	{
		if((i+1)<=size&&a[i]<a[i+1])
			i++;
		if(a[i]<temp)
			break;
		a[s]=a[i];
		s=i;
	}
	a[s]=temp;
}

void heap_sort(int a[],int n)
{
	for(int i=n/2-1;i>=0;i--)
	{
		heapAdjust(a,i,n-1);
	}

	for(int i=n-1;i>=1;i--)
	{
		swap(a[0],a[i]);
		heapAdjust(a,0,i-1);
	}
}


</pre><pre name="code" class="cpp">void merge(int *list1,int list_size1,int *list2,int list_size2)
{
	int i=0,j=0,k=0;
	int temp[MAXSIZE];
	while(i<list_size1&&j<list_size2)
	{
		if(list1[i]<list2[j])
		{
			temp[k++]=list1[i++];
		}
		else
		{
			temp[k++]=list2[j++];
		}
	}

	
		while(j<list_size2)
		{
			temp[k++]=list2[j++];
		}
	
		while(i<list_size1)
		{
			temp[k++]=list1[i++];
		}
	

	for(int m=0;m<k;m++)
	{
		list1[m]=temp[m];
	}

}

//歸併排序
void merge_sort(int a[],int n)
{
	if(n>1)
	{
		int *list1=a;
		int list_size1=n/2;
		int *list2=a+n/2;
		int list_size2=n-list_size1;
		merge_sort(list1,list_size1);
		merge_sort(list2,list_size2);
		merge(list1,list_size1,list2,list_size2);

	}
}


int partition(int a[],int low,int high)
{
	int key=a[low];
	while(low<high)
	{
		while(low<high&&a[high]>=key)
		{
			high--;
		}
		swap(a[low],a[high]);
		while(low<high&&a[low]<=key)
		{
			low++;
		}
		swap(a[low],a[high]);

	}
	return low;
}

void qsort(int a[],int low,int high)
{
	if(low<high)
	{
		int point=partition(a,low,high);
		qsort(a,low,point-1);
		qsort(a,point+1,high);
	}
}
//快速排序
void quick_sort(int a[],int n)
{
	qsort(a,0,n-1);
}
void main()
{
	int a[6]={2,8,0,1,6,3};
	//bubble_sort(a,6);
	//select_sort(a,6);
	//insert_sort(a,6);
	//shell_sort(a,6);
	//heap_sort(a,6);
	//merge_sort(a,6);
	quick_sort(a,6);
	for(int i=0;i<6;i++)
	{
		cout<<a[i]<<" ";
	}
	cout<<endl;
	system("pause");
}

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