public class insertsort {
public static void main(String[] args) {
int[] arr={3,2,7,5,9,6,-2,8};
insert_sort2(arr);
print_array(arr);
}
public static void print_array(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void insert_sort1(int[] arr){
if(arr==null || arr.length<2){
return;
}
int n = arr.length;
for(int end=1;end<n;end++){
int newNumIndex=end;
while (newNumIndex-1>=0&&arr[newNumIndex-1]>arr[newNumIndex]){
swap_location(arr,newNumIndex-1,newNumIndex);
newNumIndex--;
}
}
}
public static void insert_sort2(int[] arr){
if(arr==null || arr.length<2){
return;
}
int n = arr.length;
for(int end=1;end<n;end++){
for(int pre=end-1;pre>=0&&arr[pre]>arr[pre+1];pre--){
swap_location(arr,pre,pre+1);
}
}
}
private static void swap_location(int[] arr, int i, int j) {
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
- 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
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61