Sorting numbers in an array without sort function
Afficher commentaires plus anciens
Hello,
I want to sort numbers in an arrey without using sort function, but with bubblesort (swapping number next each other until all numbers are sorted)
Here is what I have...
X=[10 1 29 89 5 56 76 8];
finished=0;
while finished==0
if finished==0
for i=1:size(X,2)-1
if X(i)>X(i+1)
c=X(i);
X(i)=X(i+1);
X(i+1)=c;
end
end
end
if X(i)<X(i+1) || X(i)==X(i+1)
finished=1;
end
end
disp(X)
I understand that this loop works by comparing numbers next each other (like comparing 10 with 1). Then, if the front number (10) is bigger than the next number (1), the numbers are swaped. However, I want to break the loop once all numbers are sorted from the minimum number to the maximum number.
The code above only sorts the numbers until [1,10,29,5,56,76,8,89], so I want to loop several more to complete the sorting, but I want the code stops when the sorting is done. Otherwise, the code keeps on looping again and again.
I really appreciate if I get some help with this problem.
Réponse acceptée
Plus de réponses (1)
the cyclist
le 27 Nov 2019
Modifié(e) : the cyclist
le 27 Nov 2019
if all(diff(X)) >= 0
Also, rather than defining the finished variable, you could have just made that the condition for the while loop:
while not(all(diff(X)) >= 0)
or, mathematically equivalently but a bit more elegantly
while any(diff(X)) < 0
1 commentaire
Takashi Fukushima
le 27 Nov 2019
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!