Exceeding matrix dimensions for a sorting algorithm, how do I run through an entire array with just a single for loop?

Hello, so I have been trying to work on a very basic sorting algorithm that just goes thru an array of 'N' numbers and sorts them in ascending order. We can't use any built in sort functions and we get a bonus point for using a single for loop. I decided to go with a Bubble sort since I know how that works, but I don't know how to make it so that the for loop can go thru an array of any size. Here's what I have so far:
a = [1 9 2 8 3 7 4 6 5]; %My array
b = a; %temp variable
[a1, a2] = size(a); %gets the length of array
for i = 1:a2 %ensures the loop goes all the way thru the array
if a(i+1) < a(i) %checks if the follow value is greater than the lead
b(i) = a(i); %if so sets the lead value to the temp value
a(i) = a(i+1); %sets first value to follow value
a(i+1) = b(i); %sets follow value to first value
end
end
a
I understand what's wrong with this, that as the for loop approaches the end of the array, the a(i+1) exceeds the limit of the array's size. But I'm just really stuck on how I am suppose to be able to do this for any sized array. If anyone could provide any help I would greatly appreciate it. Thanks!

1 Comment

a2 = 10 ;
1 : a2
1 : a2-1
outputs:
ans =
1 2 3 4 5 6 7 8 9 10
ans =
1 2 3 4 5 6 7 8 9
but if I remember well, it will be tricky to implement bubble sort using a single explicit loop!

Sign in to comment.

Answers (0)

Categories

Asked:

on 13 Oct 2017

Edited:

on 13 Oct 2017

Community Treasure Hunt

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

Start Hunting!