-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSorting.java
More file actions
62 lines (56 loc) · 1.67 KB
/
Sorting.java
File metadata and controls
62 lines (56 loc) · 1.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
import java.util.*;
public class Sorting {
// bubble sort
public static void bubblesort(int arr[]){
for( int turn=0; turn<arr.length-1;turn++){
for(int j = 0; j<arr.length-1-turn;j++){
if(arr[j]<arr[j+1]){
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
public static void printarr(int arr[]){
for(int i =0 ; i<arr.length;i++){
System.out.print(arr[i]+"");
}
System.out.println();
}
// Selection sort
public static void selectionsort(int[] arr){
for(int i =0;i<arr.length-1 ;i++){
int smallest = i;
for(int j = i+1;j<arr.length;j++){
if(arr[smallest]>arr[j]){
smallest= j;
}
}
// swap
int temp = arr[smallest];
arr[smallest]=arr[i];
arr[i]=temp;
}
}
// insertion sort
public static void insertionsort(int[ ]arr){
for(int i =0;i<arr.length-1 ;i++){
int curr = arr[i]; // temp memory to store current
int prev = i-1;
// finding out to correct pos to insert
while(prev>=0 && arr[prev]>arr[curr]){
arr[prev+1]=arr[prev];
prev--;
}
// insertion
arr[prev+1]=arr[curr];
}
}
public static void main(String[] args) {
int arr[] = {5,4,1,3,2};
// Arrays.sort(arr); //inbuilt sort
//
printarr(arr);
}
}