当前位置:网站首页>插入排序 优化插入排序
插入排序 优化插入排序
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);
}
}
边栏推荐
猜你喜欢
金仓数据库 KingbaseES V8.3 至 V8.6 迁移最佳实践(4. V8.3 到 V8.6 数据库移植实战)
阿里官方 Redis 开发规范
C语言:表达式求值详解
2022 Strong Net Cup CTF---Strong Net Pioneer ASR wp
MLX90640 红外热成像仪测温模块开发笔记(完整版)
matlab 基于奇偶校验的LSB隐藏水印 三种改进
[Dark Horse Morning Post] Hu Jun's endorsement of Wukong's financial management is suspected of fraud, which is suspected to involve 39 billion yuan; Fuling mustard responded that mustard ate toenails
02 es 集群搭建
软测面试如何介绍项目?要做哪些技术准备?
MUI as a mobile phone to return to the action bar
随机推荐
JumpServer堡垒机部署
助推科技强国高质量发展《科创超级训练营》系列活动正式拉开帷幕
AntDB数据库亮相24届高速展,助力智慧高速创新应用
ECCV 2022 | Poseur:你以为我是姿态估计,其实是目标检测哒
二分练习题
C#的CSV格式文件帮助类
MySQL locking case analysis
素域和扩域
Isometric graph neural networks shine in drug discovery
ESP8266-Arduino programming example-GA1A12S202 logarithmic scale analog light sensor
MySQL INTERVAL Keyword Guidelines
How to Efficiently Develop Jmix Extension Components
2022.08月--pushmall推贴共享电商更新与开发计划
Using Canvas to achieve web page mouse signature effect
PAT 甲级 A1030 Travel Plan
C#的DataTable帮助类
表达式;运算符,算子;取余计算;运算符优先顺序
Financial products with high annualized returns
京东软件测试面试题,仅30题就已经拯救了50%的人
怎么安装汉化包(svn中文语言包安装)