-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting.java
84 lines (69 loc) · 1.49 KB
/
Sorting.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
//Implementing insertion sort
class Sorting{
void InsertionSort(int arr[])
{
int n=arr.length;
for(int i=1;i<n;i++)
{
int key=arr[i];
int j=i-1;
//Move elements that are greater than the key element to make space for key
while(j>=0 && arr[j]>key)
{
arr[j+1] = arr[j];
j=j-1;
}
arr[j+1]=key;
System.out.print("\nStep "+i+" : ");
printArray(arr);
}
}
void SelectionSort(int arr[])
{
int n=arr.length;
int min_index,temp;;
for(int i=0;i<n-1;i++)
{
min_index = i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
{
min_index = j;
}
}
temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
System.out.print("\nStep "+i+" : ");
printArray(arr);
}
}
void printArray(int arr[])
{
int n=arr.length;
for(int i=0;i<n;i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String args[])
{
int arr1[] = {2,7,9,5,3,8,4,1,6,0};
int arr2[] = {9,3,7,5,0,1,4,2,8,6};
Sorting obj = new Sorting();
System.out.println("-------------USING SELECTION SORT--------------");
System.out.print("\nInitial Array: ");
obj.printArray(arr1);
obj.SelectionSort(arr1);
System.out.print("\nFinal Array: ");
obj.printArray(arr1);
System.out.println("\n-------------USING INSERTION SORT--------------");
System.out.print("\nInitial Array: ");
obj.printArray(arr2);
obj.InsertionSort(arr2);
System.out.print("\nFinal Array: ");
obj.printArray(arr2);
}
}