-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSorting.java
More file actions
93 lines (82 loc) · 2.71 KB
/
Copy pathSorting.java
File metadata and controls
93 lines (82 loc) · 2.71 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
public class Sorting {
public static void Bubble(int arr[]) {
for (int turn = 0; turn < arr.length - 1; turn++) {
int swap = 0;
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;
swap++;
}
}
if (turn == 0) {
if (swap == 0) {
System.out.println("No swap");
break;
}
}
}
}
public static void Selection(int arr[]) { // n is total no. of elements
for (int i = 0; i < arr.length - 1; i++) { // to check elements from 0 index to n-2;
int minPos = i; // minimum value is assumed to be at 0 index;
for (int j = i + 1; j < arr.length; j++) { // check every value from i+1 index to n-1;HHH
if (arr[j] < arr[minPos]) {
minPos = j;
}
}
// swap
int temp = arr[minPos];
arr[minPos] = arr[i];
arr[i] = temp;
}
}
public static void Insertion(int arr[]) {
for (int i = 1; i < arr.length; i++) {
int curr = arr[i];
int prev = i - 1;
// finding out the correct position to insert
while (prev >= 0 && arr[prev] > curr) {
arr[prev + 1] = arr[prev];
prev--;
}
// insertion
arr[prev + 1] = curr;
}
}
public static void Counting(int arr[]) {
int largest = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
largest = Math.max(largest, arr[i]);
}
int count[] = new int[largest + 1];
for (int i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
// sorting
int j = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
arr[j] = i;
j++;
count[i]--;
}
}
}
public static void printarr(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
// int arr[] = { 5, 4, 1, 3, 2 };
// int arr[] = { 1, 2, 3, 5, 4 };
int arr[] = { 4, 3, 2, 4, 5, 6, 3, 4, 2, 1, 1, 7, 7 };
// Insertion(arr);
// Collection.reverseOrder() works only on object data type not primitve
// Arrays.sort(arr, 0, 3,Collection.reverseOrder()); //Inbuilt sort
Counting(arr);
printarr(arr);
}
}