-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting.java
62 lines (51 loc) · 1.34 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
public class Sorting {
//bubble sort function
static void bubbleSort(int arr[]){
for(int i=0;i<arr.length-1;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j]>arr[j+1]){
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
//selection sort
static void selectionSort(int arr[]){
for(int i=0;i<arr.length;i++){
int smallest=i;
for(int j=i+1;j<arr.length;j++){
if(arr[smallest]>arr[j]){
smallest=j;
}
}
int temp=arr[smallest];
arr[smallest]=arr[i];
arr[i]=temp;
}
}
//insertion sort
static void insertionSort(int arr[]){
for(int i=1;i<arr.length;i++){
int current=arr[i];
int j=i-1;
while(j>=0 && current <arr[j]){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=current;
}
}
//function to print array
static void printArray(int[] arr) {
for(int i=0;i<arr.length;i++){
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
int arr[]={3,7,4,8};
insertionSort(arr);
printArray(arr);
}
}