forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOddEvenSort.java
More file actions
67 lines (56 loc) · 1.66 KB
/
OddEvenSort.java
File metadata and controls
67 lines (56 loc) · 1.66 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
package Sorts;
import java.util.Random;
// https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
public class OddEvenSort {
public static void main(String[] args) {
int[] arr = new int[100];
Random random = new Random();
// Print out unsorted elements
for (int i = 0; i < arr.length; ++i) {
arr[i] = random.nextInt(100) - 50;
System.out.println(arr[i]);
}
System.out.println("--------------");
oddEvenSort(arr);
//Print Sorted elements
for (int i = 0; i < arr.length - 1; ++i) {
System.out.println(arr[i]);
assert arr[i] <= arr[i + 1];
}
}
/**
* Odd Even Sort algorithms implements
*
* @param arr the array contains elements
*/
public static void oddEvenSort(int[] arr) {
boolean sorted = false;
while(!sorted) {
sorted = true;
for(int i = 1; i < arr.length-1; i += 2){
if (arr[i] > arr [i + 1]){
swap(arr, i, i+1);
sorted = false;
}
}
for (int i = 0; i < arr.length - 1; i+= 2){
if( arr[i] > arr[i + 1] ){
swap(arr, i, i+1);
sorted = false;
}
}
}
}
/**
* Helper function to swap two array values.
*
* @param arr the array contains elements
* @param i the first index to be swapped
* @param j the second index to be swapped
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}