Write a MATLAB program which implements the BubbleSort algor
Write a MATLAB program which implements the Bubble-Sort algorithm. Show progress of the sorting. Demonstrate with a 20 element vector having random element vlaues.
Then,
Improve the Bubble Sort algorithm so that it detects if a vector is already sorted.
Demonstrate with a 20 element vector having random element vlaues.
Solution
In order to make it easier, you can generate the code by using several functions. What is more, in order to improve the system we can use a function that, before running the Bubble-sort algorithm, verifies whether the vector is already sorted.
- Verify function:
function [c] = verify(v)
c=0; %it is ordered
for i=1:length(v)-1
if v(i)>v(i+1)
c=1; % disordered
break % the loop ends
end
end
end
Now, in case that the vector is not sorted, the Bubble-Sort algorithm has to be run. However, it implies the swapping among the vector elements (in order to sort the vector). Therefore, the following function may be used:
- Swapping function
function [r] = swap(a,b)
if a>b
r(1)=b;
r(2)=a;
else
r(1)=a;
r(2)=b;
end
end
Finally, the Bubble-Sort algorithm can be applied by using the following code:
- Bubble-sort function
function [x] = bubblesort(v)
z=v;
c=verify(z); %Function shown above
while c==1 % If the vector is not sorted, the bubble-Sort algorithm is run
for i=1:length(z)-1
if z(i) > z(i+1)
x=swap(z(i),z(i+1)); %Function shown above
z(i)=x(1); %Assigning the result of the swap function
z(i+1)=x(2);
end
end
c=verify(z);
end
x=z; %Final vector - answer
end
Demonstration:
v = randi([0 300],1,20); % generating random integers values from 0 to 300 and putting them in an array that has the components from 1 to 20 (20 element vector)
Resulting the following vector:
v =
Columns 1 through 15
245 272 38 274 190 29 83 164 288 290 47 292 288 146 240
Columns 16 through 20
42 126 275 238 288
Applying the designed function:
>> y=bubblesort(v)
y =
Columns 1 through 15
29 38 42 47 83 126 146 164 190 238 240 245 272 274 275
Columns 16 through 20
288 288 288 290 292
Getting the expected solution.
NOTE:
In order to show the progess of the sorting the only thing that has to be done is this:(in the code of the Bubble-sort function):
function [x] = bubblesort(v)
z=v;
c=verify(z);
while c==1
for i=1:length(z)-1
if z(i) > z(i+1)
x=swap(z(i),z(i+1));
z(i)=x(1);
z(i+1)=x(2);
end
end
display(z); % The vector is going to be shown in every loop, showing the progress of the sorting
c=verify(z);
end
x=z;
end

