C语言复试上机(入门篇-算法初步之排序算法)

  1. 冒泡排序:
#include <stdio.h>

int main(){
	int a[5] = {1,5,8,3,0};
	int i,j,l,temp;
	for(i=1;i<5;i++)
		for(j=0;j<5-i;j++)
			if(a[j] >= a[j+1]){
				temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
			}
	for(i=0;i<5;i++)
		printf("%d",a[i]);
	return 0;
} 

2.选择排序

#include <stdio.h>

int main(){
	int a[5] = {1,5,8,3,0};	

	int temp,min,count,n=5;
	for(int i=0;i<n;i++){
		min = a[i];
		count = i;
		for(int j=i;j<n;j++){
			if(a[j]<min){
				min = a[j];
				count = j;
			}
		}
		temp = a[i];
		a[i] = a[count];
		a[count] = temp;
	}
	for(int i=0;i<n;i++)
		printf("%d ",a[i]);	
	return 0;
} 
  1. 插入排序
#include <stdio.h>

int main(){
	int a[5] = {1,5,8,3,0};
	int temp,n = 5;
	for(int i=1;i<n;i++){
		temp = a[i];
		while(a[i-1]>temp){
			a[i] = a[i-1];
			i--;
		}
		a[i] = temp;
	}
	for(int i=0;i<n;i++){
		printf("%d ",a[i]);
	}	
	return 0;
} 
  1. 快速排序
#include <stdio.h>
int Partition(int a[],int left,int right){
	int temp = a[left];
	while(left<right){
		while(left<right&&a[right]>temp)right--;
		a[left] = a[right];
		while(left<right&&a[left]<=temp)left++;  // 注意这里是小于等于号 
		a[right] = a[left];
	}
	a[left] = temp;
	return left; // 返回相遇的下标 
	
}

void quicksort(int a[],int left,int right){
	if(left<right){
		int pos = Partition(a,left,right);
		quicksort(a,left,pos-1);
		quicksort(a,pos+1,right);
	}
} 


int main(){
	int a[]={1,3,2,5,2,4,5,6};
	quicksort(a,0,7);
	for(int i=0;i<8;i++){
		printf("%d ",a[i]);
	}
	
	return 0;
} 
  1. 二路归并排序
#include <stdio.h>

const int max=100;
void merge(int a[],int L1,int R1,int L2,int R2){
	int temp[max];
	int i=0;
	int k=L1;
	while(L1<=R1&&L2<=R2){  // 注意有等号 
		if(a[L1]<a[L2]){
			temp[i++]=a[L1++];
		}else{
			temp[i++]=a[L2++];
		}
	}
	
	while(L1<=R1){  // 注意有等号 
		temp[i++] = a[L1++];
	}
	while(L2<=R2){  // 注意有等号 
		temp[i++] = a[L2++];
	}
	
	for(int j=0;j<i;j++){
		a[k+j] = temp[j];
	}
} 

void mergeSort(int a[],int left,int right){
	if(left<right){
		int mid=(left+right)/2;
		mergeSort(a,left,mid);
		mergeSort(a,mid+1,right);
		merge(a,left,mid,mid+1,right);
	}
}

int main(int argc,char **argv){
	int a[]={1,3,2,5,2,4,5,6};
	mergeSort(a,0,7);
	for(int i=0;i<8;i++){
		printf("%d ",a[i]);
	}
	
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值