Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Bubblesort Algorithm: Filling in the Array after Each Step, Exercises of Computer Programming

The bubblesort algorithm code and asks the reader to fill in the entries for the array after each step of the sorting process. The code is written in matlab and the input array is [5 4 3 1 2].

Typology: Exercises

2012/2013

Uploaded on 08/17/2013

zaid
zaid 🇮🇳

4.5

(2)

61 documents

1 / 1

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1 Sorting (100 points)
The following code sorts an array using an algorithm called bubblesort.
function x = bubblesort(x)
disp(’======================= INPUT ARRAY =============================’)
fprintf(’(Array x) ’); disp(x)
disp(’=================================================================’)
n = length(x);
step = 0;
for i=1:n-1
for j=1:n-i
if x(j) > x(j+1)
temp = x(j+1);
x(j+1) = x(j);
x(j) = temp;
end
step = step + 1;
fprintf(’(Step %2d) ’,step); disp(x);
end
fprintf(’(Pass %2d) ’,i); disp(x);
end
If we run the following script, could you fill in the entries for the array after each step?
x=[54312];
y = bublesort(x);
(Step 1)
(Step 2)
(Step 3)
(Step 4)
(Pass 1)
(Step 5)
(Step 6)
(Step 7)
(Pass 2)
(Step 8)
(Step 9)
(Pass 3)
(Step 10)
(Pass 4)
1
docsity.com

Partial preview of the text

Download Bubblesort Algorithm: Filling in the Array after Each Step and more Exercises Computer Programming in PDF only on Docsity!

1 Sorting (100 points)

The following code sorts an array using an algorithm called bubblesort.

function x = bubblesort(x)

disp(’======================= INPUT ARRAY =============================’) fprintf(’(Array x) ’); disp(x) disp(’=================================================================’)

n = length(x); step = 0; for i=1:n- for j=1:n-i if x(j) > x(j+1) temp = x(j+1); x(j+1) = x(j); x(j) = temp; end step = step + 1; fprintf(’(Step %2d) ’,step); disp(x); end fprintf(’(Pass %2d) ’,i); disp(x); end If we run the following script, could you fill in the entries for the array after each step?

x = [5 4 3 1 2]; y = bublesort(x);

(Step 1) (Step 2) (Step 3) (Step 4) (Pass 1) (Step 5) (Step 6) (Step 7) (Pass 2) (Step 8) (Step 9) (Pass 3) (Step 10) (Pass 4)

docsity.com