蓝桥杯国赛备赛复习——基础算法

一、排序

1.1 快速排序

package 排序;

import java.util.Scanner;

public class 快速排序 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		int []a = new int[110];
		int n = scan.nextInt();
		for(int i=0;i<n;i++)
			a[i] = scan.nextInt();
		Q_sort(a,0,n-1);
		for(int i=0;i<n;i++)
			System.out.print(a[i]+" ");
	}
	static void Q_sort(int a[],int l,int r) {
		if(l>=r) return;
		int x = a[l];
		int i = l - 1;
		int j = r + 1;
		while(i<j) {
			do i++; while(a[i]<x);
			do j--; while(a[j]>x);
			if(i<j) {
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
		Q_sort(a,l,j);
		Q_sort(a,j+1,r);
	}
}

1.2 归并排序

package 排序;
import java.util.*;
public class 归并排序 {
	static int []tmp = new int[110];	//辅助数组
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		int []a = new int[110];
		int n = scan.nextInt();
		for(int i=0;i<n;i++)
			a[i] = scan.nextInt();
		Merge_sort(a,0,n-1);
		for(int i=0;i<n;i++)
			System.out.print(a[i]+" ");
	}
	static void Merge_sort(int []a,int l,int r) {
		// 递归退出条件
		if(l>=r)	return;
		// 分
		int mid =  l + r >> 1;
		Merge_sort(a,l,mid);
		Merge_sort(a,mid+1,r);
		// 合
		int ans=0,x=l,y=mid+1;
		while(x<=mid&&y<=r)
			if(a[x]<=a[y])	tmp[ans++] = a[x++];
			else  tmp[ans++] = a[y++];
		while(x<=mid) tmp[ans++] = a[x++];
		while(y<=r) tmp[ans++] = a[y++];
		for(int i=l,pos=0;i<=r;i++) a[i] = tmp[pos++];
	}
}

二、二分

2.1 整数二分

package 二分;
import java.util.*;
public class 整数二分 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 模板1
		int l = 1,r = 1,mid;
		while(l<r) {
			mid = (l+r)/2;
			if(check(mid)) r = mid;
			else l = mid+1;
		}
		// 模板1
		while(l<r) {
			mid = (l+r+1)/2;
			if(check(mid)) l = mid;
			else r = mid-1;
		}
	}
	static boolean check(int x) {
		return true;
	}
}

2.2 浮点二分

package 二分;

public class 浮点二分___平方根 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int x =4;
		double l = 0,r = x;
		while((r-l) > 1e-8) {
			double mid = (l+r)/2;
			if(mid*mid>=x) r = mid;
			else l = mid;
		}
		System.out.print(l);
	}
}

上一篇:【Linux】掌握Linux系统编程中的权限与访问控制


下一篇:Elasticsearch中对文章进行索引和查重