欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

插入排序(java版)

发布时间:2025/3/15 编程问答 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 插入排序(java版) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1 public class InsertSortTest{ 2 public static void InsertSort(int[] source) { 3 //默认第一个元素已排序 4 for (int i = 1; i < source.length; i++) { 5 for (int j = i; (j > 0) && (source[j] < source[j - 1]); j--) { 6 swap(source, j, j - 1); 7 } 8 } 9 } 10 //完成交换功能的子函数 static 11 private static void swap(int[] source, int x, int y) { 12 int temp = source[x]; 13 source[x] = source[y]; 14 source[y] = temp; 15 } 16 //在main中测试 17 public static void main(String[] args) { 18 int[] a = {4, 2, 1, 6, 3, 6, 0, -5, 1, 1}; 19 20 InsertSort(a); 21 22 for (int i = 0; i < a.length; i++) { 23 System.out.printf("%d ", a[i]); 24 } 25 } 26 }

 

转载于:https://www.cnblogs.com/happyhacking/p/4350616.html

总结

以上是生活随笔为你收集整理的插入排序(java版)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。