-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertionSort.java
88 lines (85 loc) · 2.04 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.Scanner;
class insertionSort
{
Scanner sc=new Scanner(System.in);
int a[],n;
char order;
void input()
{
System.out.print("\fEnter the length of array:");
n=sc.nextInt();
a=new int[n];
System.out.print("Enter the elements of the array:");
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.print("Enter 'a' for ascending or 'd' for descending sort - ");
for(int loopvar=1;loopvar==1;)
{
order = sc.next().charAt(0);
if(order=='a' || order=='d')
loopvar++;
else
System.out.print("Wrong Input! Try again - ");
}
}
void sort()
{
int small=a[0],large=a[0],pos=0;
if(order == 'a')
{
for(int i=0;i<a.length;i++)
{
int temp = a[i];
for(int j=i;j>=0;j--)
{
if(j==0 || a[j-1]<=temp)
{
a[j]=temp;
break;
}
else
a[j]=a[j-1];
}
}
}
else
{
for(int i=0;i<n;i++)
{
if(large<a[i])
{
large=a[i];
pos=i;
}
}
a[pos]=a[0];
a[0]=large;
for(int i=1;i<n;i++)
{
int j=i,temp=a[i];
while(temp>a[j-1])
{
a[j]=a[j-1];
j=j-1;
}
a[j]=temp;
}
}
}
void print()
{
System.out.print("\nThe arranged array is: ");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+"\t");
}
}
public static void main(String args[])
{
insertionSort obj=new insertionSort();
obj.input();
obj.sort();
obj.print();
}
}
//arshiya sharma