-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.java
66 lines (58 loc) · 1.29 KB
/
InsertionSort.java
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
62
63
64
65
66
package com.algorithms;
public class InsertionSort
{
public static void main(String[] args) {
int[] myList={3,5,2,7,9,8,6,5,0,13,12};
int[] ar={1,4,3,5,6,2};
insertionSort(ar,ar.length);
//insertIntoSorted(ar);
/**
for (int i=0;i<myList.length;i++)
{
System.out.println(myList[i]);
}
**/
//System.out.println(myList.length +" Items");
}
public static void insertionSort(int[] list,int N)
{
//int length=list.length;
int j=0;
for(int i=1;i<N;i++)
{
j=i;
while(j>0 && (list[j] < list[j-1]))
{
swap(list,j,j-1);
//decrement j
j--;
}
for(int k=0;k<list.length;k++){
System.out.print(list[k]+" ");
}
System.out.println();
}
}
public static void insertIntoSorted(int[] ar) {
int s=ar.length;
int j=s-1;
for(int i=0;i<s;i++){
System.out.print(ar[i]+" ");
}
System.out.println();
while(j>0 && (ar[j] < ar[j-1])){
swap(ar,j,j-1);
j--;//decrement j
for(int i=0;i<s;i++){
System.out.print(ar[i]+" ");
}
System.out.println();
}
}
public static void swap(int[] arr,int i, int j)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}