王道数据结构排序总结-含代码

插入排序

直接插入排序

void InsertSort(ElemType A[],int n)
{
	int i,j;
	for (i = 2;i <= n;i ++)
		if (A[i] < A[i-1]) {
			A[0] = A[i];
			for (j = i-1;A[0] < A[j]; --j)
				A[j+1] = A[j];
			A[j+1] = A[0];
		}
}

折半插入排序

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

希尔排序

void ShellSort(ElemType A[],int n)
{
	for (dk = n/2;dk >= 1;dk = dk/2)
		for (i = dk+1;i <= n;i ++)
			if (A[i] < A[i-dk]) {
				A[0] = A[i];
				for (j = i-dk;j > 0&&A[0] < A[j];j -= dk)
					A[j+dk] = A[j];
				A[j+dk] = A[0];
			} 
}

交换排序

冒泡排序

void BubbleSort(ElemType A[],int n)
{
	for (i = 0;i < n-1;i ++) {
		flag = false;
		for (j = n-1;j > i;j --)
			if (A[j-1] > A[j]) {
				swap(A[j-1],A[j]);	
			}
		if (flag == false)
			return;
	}
}

快速排序

void QuickSort(ElemType A[],int low,int high)
{
	if (low < high) {
		int pivotpos = Partion(A,low,high);
		QucikSort(A,low,pivotpos-1);
		QucikSort(A,pivotpos+1,high);
	}
}

int Partition(ElemType A[],int low,int high)
{
	ElemType pivot = A[low];
	while (low < high) {
		while (low < high&&A[high]>=pivot) high --;
		A[low] = high;
		while (low < high&&A[low] <= pivot) ++low;
		A[high] = A[low];
	}
	A[low] = pivot;
	return low;
}

选择排序

简单选择排序

void Selectsort(ElemType A[],int n)
{
	for (i = 0;i < n-1;i ++) {
		min = i;
		for (j = i+1;j < n;j ++)
			if (A[j] < A[min]) min = j;
		if (min != i) Swap(A[[i],A[min]);
	}
}

堆排序

void BuildMaxHeap(Elemtype A[],int len) 
{
	for (int i = len/2;i > 0;i --)
		HeadAdjust(A,i,len);
}

void HeadAdjust(ElemType A[],int k,int len)
{
	A[0] = A[k];
	for (i = 2*k;i <= len;i *= 2) {
		if (i < len&&A[i] < A[i+1])
			i ++;
		if (A[0] >= A[i]) break;
		else {
			A[k] = A[i];
			k = i;
		}
	} 
	A[k] = A[0];
}

void HeapSort(ElemType A[],int len)
{
	BuildMaxHeap(A,len);
	for (i = len;i > 1;i --) {
		Swap(A[i],A[1]);
		HeadAdjust(A,1,i-1);	
	}
}

归并排序和基数排序

归并排序

ElemType *B = (ElemType *)malloc((n+1)*sizeof(ElemType));
void Merge(ElemType A[],int low,int mid,int high)
{
	for (int k = low;k <= high;k ++)
		B[k] = A[k];
	for (i = low,j = mid+1,k = i;i <= mid&&j <= high;k ++) {
		if (B[i] <= B[j])
			A[k] = B[i ++];
		else 
			A[k] = B[j ++];
	}
	while (i <= mid) A[k ++] = B[i ++];
	while (j <= high) A[k ++] = B[j ++];
}

void MergeSort(ElemType A[],int low,int high)
{
	if (low < high) {
		int mid = (low + high)/2;
		MergeSort(A,low,mid);
		MergeSort(A,mid+1,high);
		Merge(A,low,mid,high);
	}
}
  • 不稳定算法 快速简选希尔堆

你可能感兴趣的:(考研,数据结构,算法,排序算法)