赞
踩
- !!!排序仅针对于数组哦
- 本次排序是按照升序来的哦
<!----java-----> public static void main(String[] args) { int[] arr={10,2,3,8,1,9}; sort(arr); System.out.println(Arrays.toString(arr)); } public static void sort(int[] arr){ // 默认第一个已经排好序了,所以我们从第二个元素开始 for(int i=1;i<arr.length;i++){ // 定义游标j,依次从后往前遍历 for(int j=i;j>0;j--){ // 前一个数比当前数小,交换 if(arr[j-1]>arr[j]){ int temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } } } <!------------------------> 运行结果; [1, 2, 3, 8, 9, 10]
<!----python----->
def insertSort(arr):
for i in range(1,len(arr)):
for j in range(i,0,-1):
if arr[j-1]>arr[j]:
arr[j],arr[j-1] = arr[j-1],arr[j];
print(arr)
arr=[10,2,3,8,1,9];
insertSort(arr)
<!------------------------>
运行结果;
[1, 2, 3, 8, 9, 10]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。