各种排序代码集合笔记

#include<stdio.h>

//直接插入排序
void InsertSort(int *datatemp,int n){
	int *data = new int[n];
	for(int i=0;i<n;i++){
		data[i]=datatemp[i];
	}
	int temp,j;
	for(int i=2;i<n;i++){
		temp = data[i];
		if(data[i]<data[i-1]){
			j = i-1;
			while(data[j]>temp){
				data[j+1]=data[j];
				j--;
			}
			data[j+1]=temp;
		}
	}
	//输出
	printf("直接插入排序:\t");
	for(int i=1;i<n;i++){
		printf("%d  ",data[i]);
	}
	printf("\n");
}

//希尔排序
void ShellSort(int *datatemp,int n){
	int *data = new int[n];
	for(int i=0;i<n;i++){
		data[i]=datatemp[i];
	}
	int dk = n/2;
	while(dk>=1){
		//插入排序了下面是
		for(int i=dk;i<n;i+=dk){
			int temp = data[i];
			if(data[i]<data[i-dk]){
				int j = i-dk;
				while(data[j]>temp){
					data[j+dk]=data[j];
					j-=dk;
				}
				data[j+dk]=temp;
			}
		}
		dk/=2;
	}
	//输出
	printf("希尔排序:\t");
	for(int i=1;i<n;i++){
		printf("%d  ",data[i]);
	}
	printf("\n");
}


//快速排序
int QsortThird(int low,int high ,int *data){
	int temp = data[low];
	while(low<high){
		while(low<high && data[high]>=temp)high--;
		data[low]=data[high];
		while(data[low]<=temp && low<high) low++;
		data[high]=data[low];
	}
	data[low]=temp;
	return low;
}

void QsortSecond(int low,int high ,int *data){
	if(low<high){
		int mid = QsortThird(low,high,data);
		QsortSecond(low,mid-1,data);
		QsortSecond(mid+1,high,data);
	}
}
void QsortFrist(int *datatemp,int n){
	int *data = new int[n];
	for(int i=0;i<n;i++){
		data[i]=datatemp[i];
	}
	QsortSecond(1,n-1,data);
	//输出
	printf("快速排序:\t");
	for(int i=1;i<n;i++){
		printf("%d  ",data[i]);
	}
	printf("\n");
}

//归并排序
void Merge(int *A,int low,int mid,int high,int *B){
	int x=low,m=mid,y=mid+1,n=high;
	int k=0;
	while(x<=m && y<=n){
		  if (A[x] <= A[y]) B[k++]=A[x++];
		  else B[k++]=A[y++];
	}
	while(x<=m){
		B[k++]=A[x++];
	}
	while(y<=n){
		B[k++]=A[y++];
	}
	//把已经有序的序列再返回
	for (int i = 0; i < k; i++)  
        A[low+i] = B[i];  
}
void MergeSortSecond(int *A,int low,int high,int *B){
		if(low<high){
			int mid = (low+high)/2;
			MergeSortSecond(A,low,mid,B);
			MergeSortSecond(A,mid+1,high,B);
			Merge(A,low, mid, high, B); 
		}
}

void MergeSortFirst(int *datatemp,int n){
	int *data = new int[n];
	for(int i=0;i<n;i++){
		data[i]=datatemp[i];
	}
	int *datatmp = new int[n];
	MergeSortSecond(data,1,n-1,datatmp);

	//输出
	printf("归并排序:\t");
	for(int i=1;i<n;i++){
		printf("%d  ",data[i]);
	}
	printf("\n");
}

//堆排序
void HeapSort(){

}
int main(){
	int data[8]={0,49,38,65,97,76,13,27};//后七个数是数据,第一个是哨兵,这里为了做例子才这么写
	//输出
	printf("原始数据:\t");
	for(int i=1;i<8;i++){
		printf("%d  ",data[i]);
	}
	printf("\n");
	InsertSort(data,8);
	ShellSort(data,8);
	QsortFrist(data,8);
	MergeSortFirst(data,8);
	return 0;
}



还没写完,有空把堆排序补上。

点赞