手写一些常见算法

ops/2025/3/17 14:31:20/

手写一些常见算法

    • 快速排序
    • 归并排序
    • Dijkstra
    • 自定义排序
    • 交替打印0和1
    • 冒泡排序
    • 插入排序
    • 堆排序

快速排序

java">public class Main {public static void main(String[] args) {int nums[] = {1,3,2,5,4,6,8,7,9};quickSort(nums,0,nums.length - 1);}private static void quickSort(int[] nums, int left, int right) {if(left >= right)return;// 划分数组 得到以privot为中心的数组 左小于privot 右大于privotint privot = partition(nums, left, right);// 递归左边和右边quickSort(nums, left, privot - 1);quickSort(nums,privot + 1, right);}private static int partition(int[] nums, int left, int right) {// 选基准int p = nums[right];// 指向大于等于基准元素的前一个位置int l = left - 1;for(int r = 0; r < right; r++){if(nums[r] < p){l++;int tmp = nums[r];nums[r] = nums[l];nums[l] = tmp;}}// 再对基准元素放置l+1处,因为l是指向前一个大于等于基准的位置nums[right] = nums[l + 1];nums[l + 1] = p;return l + 1;}
}

归并排序

java">public class QuickAndMerge {static int res = 0;public static void main(String[] args) {int nums[] = {1,3,2,5,4,6,8,7,9};int res[] = mergeSort(nums, 0, nums.length - 1);quickSort(nums,0,nums.length - 1);}private static int[] mergeSort(int nums[], int left, int right){// 当排序长度为1,直接返回对应元素if(left == right)return new int[]{nums[left]};// 划分int mid = (right - left)/2 + left;int l[] = mergeSort(nums, left, mid);int r[] = mergeSort(nums, mid + 1, right);return mergeTwoArray(l,r);}private static int[] mergeTwoArray(int l[], int r[]){int res[] = new int[l.length + r.length];int num = 0;int l_num = 0;int r_num = 0;// 依次选取两数组中较小的元素while(l_num < l.length && r_num < r.length){res[num++] = l[l_num] < r[r_num] ? l[l_num++]:r[r_num++];}// 处理剩余元素while(l_num < l.length){res[num++] = l[l_num++];}while(r_num < r.length){res[num++] = r[r_num++];}return res;}

Dijkstra

java">public class Main{public static void main(String[] args) {int n = Integer.MAX_VALUE/2;int node[] = {1,2,3,4,5};int matrix[][] = new int[node.length + 1][node.length + 1];matrix[1] = new int[]{n, 0, 1, n, 3, n};matrix[2] = new int[]{n, n, 0, 3, 1, n};matrix[3] = new int[]{n, n, n, 0, n, 1};matrix[4] = new int[]{n, n, n, 1, 0, n};matrix[5] = new int[]{n, n, n, n, n, 0};// 求1到其它点的最短距离int distance[] = {n, 0, n, n, n, n};// 每次从一点开始搜索boolean accessed[] = new boolean[node.length + 1];// 共node.length个点for(int i = 0; i < node.length; i++){int curIndex = findMin(distance, accessed);accessed[curIndex] = true;// 如果有更短路径则更新for(int j = 1; j < distance.length; j++){if(curIndex != j && distance[j] > matrix[curIndex][j] + distance[curIndex]){distance[j] = matrix[curIndex][j] + distance[curIndex];}}}System.out.println(distance[5]);}// 找最小distance的一个,易得起始节点到此点的距离已最小,可以开始对其邻居进行访问private static int findMin(int[] distance, boolean[] accessed) {int index = 1;int min = Integer.MAX_VALUE;for(int i = 1; i < distance.length; i++){if(!accessed[i] && min > distance[i]){min = distance[i];index = i;}}return index;}
}

自定义排序

java">import java.util.Arrays;
import java.util.Comparator;
public class Student{int score;int age;Student(int score, int age){this.score = score;this.age = age;}public int getScore() {return score;}public void setNum(int score) {this.score = score;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public static void main(String[] args) {Student stu[] = new Student[3];stu[0] = new Student(1,2);stu[1] = new Student(1,0);stu[2] = new Student(2,0);// 写法1 匿名内部类Arrays.sort(stu, new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {if(o1.getScore() != o2.getScore())return o2.getScore() - o1.getScore();return o1.getAge() - o2.getAge();}});// 写法2 lambdaArrays.sort(stu, ((o1, o2) -> {if(o1.getScore() != o2.getScore())return o2.getScore() - o1.getScore();return o1.getAge() - o2.getAge();}));// 写法3Arrays.sort(stu, Comparator.comparing(Student::getScore).reversed().thenComparing(Student::getAge));}
}

交替打印0和1

java">public class Main{private static final Object lock = new Object();private static int count = 0;private static final int MAX = 200;public static void main(String[] args) {// 创建线程 将实现了Runnable接口的printer放入,start启动Thread thread1 = new Thread(new Printer(), "线程1");Thread thread2 = new Thread(new Printer(), "线程2");thread1.start();thread2.start();}static class Printer implements Runnable {// 重写Run方法@Overridepublic void run() {while (true) {// synchronizedsynchronized (lock) {// 打印完成if (count > MAX) {break;}System.out.println(Thread.currentThread().getName() + "打印数字: " + count++);// 唤醒等待锁的线程lock.notify();try {if (count <= MAX) {lock.wait();}} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}}
}

冒泡排序

java">public class BubbleSort {public static void main(String[] args) {int bubble[] = {8,7,6,5,4,3,2,1};//bubbleSort(bubble);bubbleSortDesc(bubble);}private static void bubbleSort(int[] bubble) {for(int i = 0; i < bubble.length; i++){int flag = 0;for(int j = 0; j < bubble.length - i - 1; j++){if(bubble[j] < bubble[j + 1]){swap(bubble, j, j + 1);flag = 1;}}if(flag == 0)break;}}private static void bubbleSortDesc(int[] bubble) {for(int i = 0; i < bubble.length; i++){int flag = 0;for(int j = 0; j < bubble.length - i - 1; j++){if(bubble[j] > bubble[j + 1]){swap(bubble, j, j + 1);flag = 1;}}if(flag == 0)break;}}private static void swap(int bubble[], int i, int j){int temp = bubble[i];bubble[i] = bubble[j];bubble[j] = temp;}
}

插入排序

java">public class InsertSort {public static void main(String[] args) {int insert[] = {1,4,2,6,3,5,8,7};insertSort(insert);}private static void insertSort(int[] insert) {for(int i = 1; i < insert.length; i++){int i2 = i;int temp = insert[i2];while (i2 > 0 && temp < insert[i2 - 1]){insert[i2] = insert[i2 - 1];i2--;}insert[i2] = temp;}}
}

堆排序

java">public class HeapSort {public static void main(String[] args) {int nums[] = {1,3,4,2,6,5};heapSort(nums);}public static void heapSort(int[] nums) {int n = nums.length;// 挑整数组位置,使得父节点大于子节点,从最后一个非叶子节点开始for (int i = n / 2 - 1; i >= 0; i--) {adjust(nums, n, i);}// 依次从堆中提取元素,for (int i = n - 1; i > 0; i--) {// 将当前父节点移动到末尾int tmp = nums[0];nums[0] = nums[i];nums[i] = tmp;// 移动到末尾后继续调整堆adjust(nums, i, 0);}}private static void adjust(int[] nums, int n, int i) {// i表示父节点int largest = i;int left = 2 * i + 1; // 左子节点int right = 2 * i + 2; // 右子节点// 如果左子节点大于根节点if (left < n && nums[left] > nums[largest]) {largest = left;}// 如果右子节点大于当前最大值if (right < n && nums[right] > nums[largest]) {largest = right;}// 如果最大值不是根节点 交换节点位置,使得较大一方到父节点位置if (largest != i) {int tmp = nums[i];nums[i] = nums[largest];nums[largest] = tmp;// 调整交换后子节点所在的子树adjust(nums, n, largest);}}
}

http://www.ppmy.cn/ops/166515.html

相关文章

前沿科技展望未来发展趋势

生物技术正在改变能源行业。科学家用它来制造生物能源&#xff0c;这种能源能减少污染。生物技术能让植物快速生长&#xff0c;比如玉米、甘蔗&#xff0c;这些作物能变成燃料。把它们加工后就能做成乙醇&#xff0c;汽车可以用这种燃料。 生物技术还能改造微生物&#xff0c;…

【论文阅读】LightTS:少即是多:基于轻采样的MLP结构的快速多元时间序列预测

Less Is More: Fast Multivariate Time Series Forecasting with Light Sampling-oriented MLP Structures 原文链接&#xff1a;Less Is More: Fast Multivariate Time Series Forecasting with Light Sampling-oriented MLP Structures 目录 原文 摘要 1.引言 2.相关工作 统…

数据结构——环形数组

环形数组 start 指向第一个有效元素的索引&#xff0c;end 指向最后一个有效元素的下一个位置索引。 注意&#xff1a; start是闭区间&#xff0c;先左移后赋值&#xff0c;先赋值(null)后右移&#xff1b;end是开区间&#xff0c;先赋值再右移&#xff0c;先左移再赋值(null…

idea中lombok插件的安装与使用

idea中lombok插件的安装与使用 1.在pom文件中添加lombok依赖 <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>RELEASE</version><scope>provided</scope> </dependenc…

【MySQL】数据库开发技术:内外连接与表的索引穿透深度解析

**前言:**本节内容主要讲解表的内连和外连以及索引的一部分。 注意&#xff1a; 索引是很重要的知识点。务必学习&#xff01;&#xff01;本节将会主要谈一谈什么是索引&#xff0c;如何理解索引。 以及怎么理解MySQL与磁盘的关系。 下面友友们开始学习吧&#xff01; ps&…

Word 小黑第21套

对应大猫22 设置表格为页面的80%&#xff1a;表布局 -属性 -表格 指定宽度80% 度量单位改成百分比 段落组 -中文版式 在表格上下方留一行空段&#xff08;如果表格太大改一下样式&#xff09;插入横线 边框线 &#xff08;右击横线 -图片 修改样式&#xff09; 段落 -取消对于…

Dify使用部署与应用实践

最近在研究AI Agent&#xff0c;发现大家都在用Dify&#xff0c;但Dify部署起来总是面临各种问题&#xff0c;而且我在部署和应用测试过程中也都遇到了&#xff0c;因此记录如下&#xff0c;供大家参考。Dify总体来说比较灵活&#xff0c;扩展性比较强&#xff0c;适合基于它做…

数据库的基本概念

在当今数字化的世界中&#xff0c;数据已成为企业和组织最宝贵的资产之一。有效地管理和利用这些数据对于决策制定、服务优化和业务增长至关重要。数据库作为存储、管理及检索数据的核心工具&#xff0c;在现代信息系统中扮演着至关重要的角色。本文将介绍数据库的一些基本概念…