-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSorting.java
More file actions
121 lines (103 loc) · 2.59 KB
/
Sorting.java
File metadata and controls
121 lines (103 loc) · 2.59 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
public class Sorting {
/**
* @param args
*/
public static void main (String[] args)
{
// objects creation
Sort sort= new Sort();
int[] arr={3,2,5,4,7,1};
System.out.println("before");
Sorting.display(arr);
// sort.selectionSort(arr);
// sort.insertionSort(arr);
// sort.bubbleSort(arr);
sort.mergeSort(arr, 0, arr.length-1);
System.out.println("After :");
Sorting.display(arr);
}
static void display(int[] a)
{
for(int i=0; i<a.length; i++)
{
System.out.print(a[i]+"\t");
}
System.out.println();
}
}
class Sort{
void selectionSort(int[] a)
{
/*
*select smallest from outer loop length
*/
for(int i =0; i< a.length-1; i++)
{
int smallestIndex= i;
for(int j=i+1; j< a.length; j++)
{
if(a[j]< a[smallestIndex])
{
smallestIndex= j;
}
}
int temp= a[i];
a[i]= a[smallestIndex];
a[smallestIndex]= temp;
}
}
void insertionSort(int[] a)
{
// a[0 ] is always sorted
for(int i=1; i< a.length; i++)
{
/*
int j=i;
while( j>0 && a[j] < a[j-1] ) //j-1 is sorted part
{
int temp= a[j];
a[j]= a[j-1];
a[j-1]= temp;
j--;
}
*/
for(int j=i; j>0; j--)
{
if(a[j]< a[j-1])
{
int temp= a[j];
a[j]= a[j-1];
a[j-1]= temp;
}
}
}
}
void bubbleSort(int[] a)
{
for(int i=0; i< a.length-1; i++)
{
for(int j=0; j< a.length-1-i; j++ )
{
if (a[j]> a[j+1])
{
int temp= a[j];
a[j]= a[j+1];
a[j+1]= temp;
}
}
}
}
void mergeSort(int[] a, int left, int right)
{
if(left>= right) return;
int mid= (left+ right)/2;
mergeSort(a, left, mid);
mergeSort(a, mid+1, right);
merge(a, left, mid, right);
}
void merge(int[] a, int l, int m, int r)
{
for (int i = 0; i < mid+1; i++) {
}
}
}