odd-even transposition Algorithm

1 回表示 (過去 30 日間)
hadi
hadi 2014 年 10 月 28 日
コメント済み: hadi 2014 年 10 月 28 日
Hi
the following code is about odd-even sort algorithm in C++
void OddEvenSort(T a[], int n)
{
for (int i = 0; i < n; ++i)
{
if (i & 1)
{
for (int j = 2; j < n; j+=2)
if (a[j] < a[j-1])
swap(a[j-1], a[j]);
}
else
{
for (int j = 1; j < n; j+=2)
if (a[j] < a[j-1])
swap(a[j-1], a[j]);
}
}
how to convert this code in MATLAB? ??
  1 件のコメント
Adam
Adam 2014 年 10 月 28 日
Just program it in a function. Apart from 'swap' which you will have to program a trivial equivalent of yourself it doesn't seem to present any challenges. If you are completely new to Matlab then you need to start with the Matlab help basics and tutorials.

サインインしてコメントする。

回答 (1 件)

yonatan gerufi
yonatan gerufi 2014 年 10 月 28 日
if your array is called "arr", simple code that will do the work is:
odd =mod(arr,2);
odd_arr = arr.*odd;
odd_arr(odd_arr==0) = [];
even = ~odd;
even_arr = arr.*even;
even_arr(even_arr==0) = [];
final_arr = [even_arr, odd_arr];
  1 件のコメント
hadi
hadi 2014 年 10 月 28 日
thanks
but I do not understand your code yonatan gerufi!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by