当前位置:网站首页>插入排序 优化插入排序
插入排序 优化插入排序
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);
}
}边栏推荐
猜你喜欢

MLX90640 红外热成像仪测温模块开发笔记(完整版)

LeetCode第 303 场周赛

暑气渐敛,8月让我们开源一夏!

京东软件测试面试题,仅30题就已经拯救了50%的人

2022强网杯CTF---强网先锋 ASR wp

Using Canvas to achieve web page mouse signature effect

今晚直播!

70后夫妻给苹果华为做“雨衣”,三年进账7.91亿

Ali's official Redis development specification

ESP8266-Arduino programming example-GA1A12S202 logarithmic scale analog light sensor
随机推荐
C#的DataTable帮助类
Winform message prompt box helper class
2022年深圳市促进大健康产业集群高质量发展的若干措施
关于2022年深圳市福田区支持高端服务业发展项目的申报通知
Winform的消息提示框帮助类
Vulnhub靶机:HARRYPOTTER_ NAGINI
【paper】Cam2BEV论文浅析
请问数据库中报错信息如下,mongoshake 有什么配置的方式解决这种大消息问题吗?
【Unity,C#】哨兵射线触发器模板代码
PHP security flaws: session hijacking, cross-site scripting, SQL injection and how to fix them
年化收益高的理财产品
【TDP加码福利】COS用户实践征文月,等你来投稿!!!
matlab 基于奇偶校验的LSB隐藏水印 三种改进
助推科技强国高质量发展《科创超级训练营》系列活动正式拉开帷幕
08 spark 集群搭建
缓存一致性MESI与内存屏障
阿里官方 Redis 开发规范
【R语言】线性混合模型进行重复测量设计分析
关系运算符和if,else语句
软件测试谈薪技巧:同为测试人员,为什么有人5K,有人 20K?