1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
package com.my;
public class Sort {
//插入排序 public void insertSort(int[] arr){ int i,j,len=arr.length; for (i = 1; i < len; ++ i){ int key = arr[i]; j = i-1; while (key < arr[j] && j>=0){ arr[j+1] = arr[j]; j--; } arr[j+1] = key; } }
public void selectSort(int[] arr){ int i,j,min,len=arr.length; for (i=0; i<len-1;++i){ min = i; for (j=i+1; j<len;++j){ if (arr[j] < arr[min]){ min = j; } } if (min != i){ int tmp = arr[i]; arr[i] = arr[min]; arr[min] = tmp; } } }
public static void main(String[] args) { int[] arr = {1,3,8,2,80,1,2,34}; Sort sort = new Sort(); int[] arr1 = arr.clone(); int[] arr2 = arr.clone(); sort.insertSort(arr1); for (int i : arr1) { System.out.print(i+","); } System.out.println(); sort.selectSort(arr2); for (int i : arr2) { System.out.print(i+","); } } }
|
近期评论