-
Notifications
You must be signed in to change notification settings - Fork 368
/
Odd_Even_Sort.java
47 lines (39 loc) · 959 Bytes
/
Odd_Even_Sort.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
import java.io.*;
class Odd_Even_Sort {
public static void oddEvenSort(int arr[], int n)
{
boolean isSorted = false; // Initially array is unsorted
while (!isSorted) {
isSorted = true;
int temp = 0;
// Perform Bubble sort on odd indexed element
for (int i = 1; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
isSorted = false;
}
}
// Perform Bubble sort on even indexed element
for (int i = 0; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
isSorted = false;
}
}
}
return;
}
public static void main(String[] args)
{
int arr[] = {50, 10, 2, -4, 0};
int n = arr.length;
oddEvenSort(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println(" ");
}
}