Bubble sort that stops running when sorted

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

 Réponse acceptée

James Tursa
James Tursa le 9 Avr 2018
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

Plus de réponses (0)

Catégories

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by