-
Notifications
You must be signed in to change notification settings - Fork 0
/
OddEvenSort.java
47 lines (37 loc) · 966 Bytes
/
OddEvenSort.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
package sorting;
public class OddEvenSort {
public static void main(String []args) {
int[] arr = {2,5,6,4,11,22,10,1};
System.out.println("Before Sorting:");
for(int j=0; j<arr.length; j++)
System.out.print(arr[j] + " ");
oddEvenSort(arr);
System.out.println("\n\nAfter Sorting:");
for(int j=0; j<arr.length; j++)
System.out.print(arr[j] + " ");
}
public static void oddEvenSort(int[] arr) {
boolean sort = false;
while(!sort) {
sort = true;
//For odd index
for(int i=1; i<arr.length-1; i += 2) {
if (arr[i] > arr[i+1]) {
int tem = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tem;
sort = false;
}
}
//For even index
for(int i=0; i<arr.length; i += 2) {
if (arr[i] > arr[i+1]) {
int tem = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tem;
sort = false;
}
}
}
}
}