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

 채택된 답변

James Tursa
James Tursa 2018년 4월 9일

0 개 추천

Typically you have a variable that keeps track of whether you did a swap or not in your most recent loop. E.g.,
did_a_swap = 0;
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;
did_a_swap = 1;
end
:
end
if( ~did_a_swap )
break; % didn't do a swap, so everything is sorted. Break out of outer loop.
end

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

태그

Community Treasure Hunt

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

Start Hunting!

Translated by