当前位置:网站首页>插入排序 优化插入排序
插入排序 优化插入排序
2022-08-01 16:54:00 【Elvin域文】
package Code01;
import java.util.Scanner;
public class factorial {
// 求1~N的阶乘之和 1!+2!+3+ ... + N!
public static void fac_one(int m){
int rec = 1;
int sum = 0;
for(int j=1;j<=m;j++){
rec = rec*j;
sum += rec;
}
System.out.print(sum);
}
// 交换函数
public static void swap(int[] arr, int a, int b){
int tmp = arr[b];
arr[b] = arr[a];
arr[a] = tmp;
}
// 插入排序
public static void insertSort(int[] arr){
if(arr==null || arr.length<2){
return;
}
//0~0 完成
//0~1
//0~2
//0~3
//0~n-1
int N = arr.length;
for(int end=1;end < N;end++){
int newNumIndex = end;
while(newNumIndex-1 >=0 && arr[newNumIndex-1] > arr[newNumIndex]){
swap(arr, newNumIndex-1, newNumIndex);
newNumIndex--;
}
}
}
// 优化插入排序
public static void optinsertSort(int[] arr){
if(arr==null || arr.length<2){
return;
}
int N = arr.length;
for(int end=0; end<N; end++){
for(int pre = end-1; pre>=0 && arr[pre]>arr[pre+1]; pre-- ){
swap(arr, pre, pre+1);
}
}
}
public static void printArray(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args){
int[] arr = {7,1,3,5,1,6,8,1,3,5,7,5,6};
printArray(arr);
insertSort(arr);
printArray(arr);
optinsertSort(arr);
printArray(arr);
}
}边栏推荐
猜你喜欢

The site is not found after the website is filed. You have not bound this domain name or IP to the corresponding site! The configuration file does not take effect!

泰国 好产品推荐!2022年最好的胶原蛋白评测有哪些? 喝出健康和美丽适合需要改善肌肤

My new book has sold 10,000 copies!

The anxiety of the post-90s was cured by the vegetable market

软测面试如何介绍项目?要做哪些技术准备?

MySQL's maximum recommended number of rows is 2000w, is it reliable?

今晚直播!

LeetCode第 303 场周赛

Complete knapsack problem to find the number of combinations and permutations

网站备案后没有找到站点 您没有将此域名或IP绑定到对应站点! 配置文件未生效!
随机推荐
如何有效地开发 Jmix 扩展组件
LeetCode第 303 场周赛
银行案例|Zabbix跨版本升级指南,4.2-6.0不香吗?
2022年深圳市临床医学研究中心申请指南
C# LibUsbDotNet 在USB-CDC设备的上位机应用
个人日记
夸克网盘资源站
完全背包问题求组合数和排列数
每日优鲜大败局
【R语言】批量重命名文件
03 gp 集群搭建
深圳市商务局2022年度中央资金(跨境电子商务企业市场开拓扶持事项)申报指南
京东软件测试面试题,仅30题就已经拯救了50%的人
C#Excel帮助类
等变图神经网络在药物研发中大放异彩
zabbix部署和简单使用
关于2022年深圳市福田区支持高端服务业发展项目的申报通知
开发工具:第五章:使用idea生成实体类
探讨if...else的替代方案
华盛顿大学、Allen AI 等联合 | RealTime QA: What's the Answer Right Now?(实时 QA:现在的答案是什么?)