Skip to content

Commit 931f0e5

Browse files
authored
Merge pull request TheAlgorithms#243 from MustafaSalih1993/master
OddEvenSort Added
2 parents 06ec86c + 1f429e6 commit 931f0e5

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Sorts/OddEvenSort.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
odd–even sort or odd–even transposition sort
3+
is a relatively simple sorting algorithm, developed originally for use on parallel processors with local interconnections.
4+
It is a comparison sort related to bubble sort, with which it shares many characteristics.
5+
6+
for more information : https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
7+
*/
8+
9+
// Helper function to swap array items
10+
function swap (arr, i, j) {
11+
const tmp = arr[i]
12+
arr[i] = arr[j]
13+
arr[j] = tmp
14+
}
15+
16+
function oddEvenSort (arr) {
17+
let sorted = false
18+
while (!sorted) {
19+
sorted = true
20+
for (let i = 1; i < arr.length - 1; i += 2) {
21+
if (arr[i] > arr[i + 1]) {
22+
swap(arr, i, i + 1)
23+
sorted = false
24+
}
25+
}
26+
for (let i = 0; i < arr.length - 1; i += 2) {
27+
if (arr[i] > arr[i + 1]) {
28+
swap(arr, i, i + 1)
29+
sorted = false
30+
}
31+
}
32+
}
33+
}
34+
const testArray = [5, 6, 7, 8, 1, 2, 12, 14, 5, 3, 2, 2]
35+
36+
// Array before sort
37+
console.log(testArray)
38+
oddEvenSort(testArray)
39+
// Array after sort
40+
console.log(testArray)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy