插入排序java
Posted CS Toper之路
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了插入排序java相关的知识,希望对你有一定的参考价值。
0. 说明
1. 插入排序
2. Java 实现
public class InsertSort {
public static int[] sort(int[] arr) throws Exception {
for (int i = 0; i < arr.length - 1; i++) {
int tmp = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[tmp] > arr[j]) {
tmp = j;
}
}
if (tmp != i) {
int tmpValue = arr[i];
arr[i] = arr[tmp];
arr[tmp] = tmpValue;
}
}
return arr;
}
}
测试代码:
@Test
public void test_bubble_sort() throws Exception {
int[] arr = {6,4,2,8,3,5};
arr = InsertSort.sort(arr);
System.out.println(Arrays.toString(arr));
int[] arr2 = new int[100];
Random random = new Random(10000);
for (int i = 0 ; i < 100; i++) {
arr2[i] = random.nextInt(10000);
}
System.out.println(Arrays.toString(arr2));
arr2 = InsertSort.sort(arr2);
System.out.println(Arrays.toString(arr2));
}
[2, 3, 4, 5, 6, 8]
[2208, 572, 9116, 3475, 4500, 9574, 5641, 9166, 9727, 7670, 3030, 6816, 2621, 2172, 8074, 7634, 7455, 3468, 5423, 4888, 3594, 3684, 5136, 363, 4111, 6762, 4480, 4705, 3924, 4626, 72, 6234, 9073, 2345, 6824, 9818, 616, 5521, 4831, 30, 1515, 6297, 3430, 7197, 5985, 8791, 9926, 9276, 2467, 165, 8650, 9054, 8881, 326, 479, 1079, 7714, 5235, 2119, 9051, 456, 6343, 1629, 2903, 4130, 1667, 1219, 4171, 2075, 3998, 1896, 8627, 2752, 205, 565, 9185, 718, 9435, 8710, 25, 473, 1909, 9798, 8473, 7050, 4229, 9859, 8290, 4896, 3176, 1808, 6647, 4743, 2942, 2249, 4657, 2598, 3790, 9841, 5276]
[25, 30, 72, 165, 205, 326, 363, 456, 473, 479, 565, 572, 616, 718, 1079, 1219, 1515, 1629, 1667, 1808, 1896, 1909, 2075, 2119, 2172, 2208, 2249, 2345, 2467, 2598, 2621, 2752, 2903, 2942, 3030, 3176, 3430, 3468, 3475, 3594, 3684, 3790, 3924, 3998, 4111, 4130, 4171, 4229, 4480, 4500, 4626, 4657, 4705, 4743, 4831, 4888, 4896, 5136, 5235, 5276, 5423, 5521, 5641, 5985, 6234, 6297, 6343, 6647, 6762, 6816, 6824, 7050, 7197, 7455, 7634, 7670, 7714, 8074, 8290, 8473, 8627, 8650, 8710, 8791, 8881, 9051, 9054, 9073, 9116, 9166, 9185, 9276, 9435, 9574, 9727, 9798, 9818, 9841, 9859, 9926]
3. 总结
以上是关于插入排序java的主要内容,如果未能解决你的问题,请参考以下文章