-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingAlgorithmsPractice.java
More file actions
99 lines (92 loc) · 2.67 KB
/
SortingAlgorithmsPractice.java
File metadata and controls
99 lines (92 loc) · 2.67 KB
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
import java.util.Arrays;
import static java.lang.Integer.MAX_VALUE;
public class SortingAlgorithmsPractice {
public static void bubbleSort(int[] arr){
for(int i=0;i<arr.length;i++){
for(int j=1;j<arr.length-i;j++){
if(arr[j]<arr[j-1]){
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
for(int a:arr){
System.out.print(a+" ");
}
System.out.println();
}
for(int a:arr){
System.out.print(a+" ");
}
System.out.println();
}
public static void selectionSort(int[] arr){
for(int i=0;i<arr.length;i++){
int smallest = MAX_VALUE;
int smallIndex = i;
for(int j=i;j<arr.length;j++){
if(arr[j]<smallest){
smallest = arr[j];
smallIndex = j;
}
}
int temp = arr[i];
arr[i] = smallest;
arr[smallIndex] = temp;
for(int a:arr){
System.out.print(a+" ");
}
System.out.println();
}
for(int a:arr){
System.out.print(a+" ");
}
}
public static void mergeSort(int[] arr){
if(arr.length<2){
return;
}
int middle = arr.length/2;
int[] left = new int[middle];
int[] right = new int[arr.length-middle];
for(int i=0;i<middle;i++){
left[i] = arr[i];
}
for(int i=middle;i<arr.length;i++){
right[i-middle] = arr[i];
}
mergeSort(left);
mergeSort(right);
merge(left,right,arr);
}
public static void merge(int[] left, int[] right, int[] arr){
int i=0;
int j=0;
int k=0;
while(i<left.length && j<right.length){
if(left[i]<=right[j]){
arr[k++] = left[i++];
}else{
arr[k++] = right[j++];
}
}
while(j<right.length){
arr[k++] = right[j++];
}
while(i<left.length){
arr[k++] = left[i++];
}
}
public static void main(String[] args) {
int[] arr = {3,4,1,7,5,2};
System.out.println("Bubble Sort >>>>>>>>>>>");
bubbleSort(arr);
arr = new int[]{3, 4, 1, 7, 5, 2};
System.out.println("Selection Sort >>>>>>>>>>>");
selectionSort(arr);
arr = new int[]{4,5,1,9,2};
System.out.println("\nMerge Sort >>>>>>>>>>>");
mergeSort(arr);
System.out.println(Arrays.toString(arr));
}
}