What Mistake I am making in the code

1 回表示 (過去 30 日間)
Manav Divekar
Manav Divekar 2021 年 11 月 4 日
回答済み: Steven Lord 2021 年 11 月 4 日
I want to randomly pick two numbers from [39 25 91 71] swap it. and use while loop so that it swaps continuely until the vector is sorted. and display the sorted vector.
function out = sortbyrandomswaps(n)
x = 0;
y = 0;
while ~ all(diff(n)>=0)
x = n(randi(numel(n)));
y = n(randi(numel(n)));
x = a;
y = x;
a = y;
end
out = all(diff(n)>=0);

採用された回答

Yongjian Feng
Yongjian Feng 2021 年 11 月 4 日
編集済み: Yongjian Feng 2021 年 11 月 4 日
Maybe this:
sortbyrandomswaps([5 4 3 2 1]);
function out = sortbyrandomswaps(n)
while ~ all(diff(n)>=0)
idx1 = randi(numel(n));
idx2 = randi(numel(n));
a = n(idx2);
n(idx2) = n(idx1);
n(idx1) = a;
disp(n); % for debug only. Remove it if everything works.
end
out = all(diff(n)>=0);
end

その他の回答 (1 件)

Steven Lord
Steven Lord 2021 年 11 月 4 日
FYI you can perform a swapping operation in one step without needing an explicit temporary:
x = (1:10).^2
x = 1×10
1 4 9 16 25 36 49 64 81 100
toSwap = [4 7]
toSwap = 1×2
4 7
x(toSwap) = x(flip(toSwap)) % key step
x = 1×10
1 4 9 49 25 36 16 64 81 100
You could generalize this a bit if you wanted to swap a series of elements.
toSwap2 = [2 5 3 8 1];
x(toSwap2) = x(circshift(toSwap2, 1))
x = 1×10
64 1 25 49 4 36 16 9 81 100
The second element of x goes to position 5, the fifth to position 3, the third to position 8, the eighth to position 1, and the first to position 2.

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by