Bubble sort that stops running when sorted
Ältere Kommentare anzeigen
I am having trouble figuring out how to get my bubble sort program to end when it is fully sorted.
% %Bubble Sort V3_C%
clear all;clc
% Generate 10 integer random numbers
range = [1 10];
total_num = 10;
index = 1:total_num;
pause_sec = 0.01;
num = randi(range,1,total_num);
nums = num;
l_num = length(num);
end_ind = 1;
for j = 1:(l_num - 1)
end_ind = end_ind+1
for i = l_num:-1:end_ind
if nums(i) > nums(i-1)
tmp = nums(i);
nums(i) = nums(i-1);
nums(i-1) = tmp;
end
home
fprintf('j = %4i i = %4i \n' ,j,i)
fprintf('\n')
prtTable02(num,nums)
figure(1)
bar(nums)
hold on
bar([i,i-1],[nums(i),nums(i-1)],'r')
hold off
pause(pause_sec)
end
end
clc;home
fprintf('end \n')
prtTable02(num,nums)
This is the function prtTable02(num,nums)
function prtTable02(num,nums)
table = [num;nums];
fprintf(' num num sorted\n')
fprintf('%5i %5i \n',table)
pause(.1)
end
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!