-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSort.java
102 lines (63 loc) · 1.63 KB
/
Sort.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package com.test.java;
public class Sort {
private void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
int temp;
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("Bubble sort : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
private void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
System.out.println("Selection sort : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public void insertionSort(int[] arr) {
for (int i=1; i<arr.length; i++) { // Insertion sort starts from second element.
int key = arr[i];
int j = i - 1;
while ((j > -1) && (arr[j] > key)) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
System.out.println("Insertion sort : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
Sort sort = new Sort();
int[] arr = new int[] { 3, 2, 4, 65, 21, 54, 452, 78, 98, 34 };
sort.bubbleSort(arr);
System.out.println();
arr = new int[] { 3, 2, 4, 65, 21, 54, 452, 78, 98, 34 };
sort.selectionSort(arr);
System.out.println();
arr = new int[] { 3, 2, 4, 65, 21, 54, 452, 78, 98, 34 };
sort.insertionSort(arr);
System.out.println();
}
}