Bubble sort for loop
    124 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Matpar
 el 3 de Oct. de 2019
  
    
    
    
    
    Comentada: Guillaume
      
      
 el 4 de Oct. de 2019
            Hi can a professional guide me in terms of a bubble sort using 2 for loops please!
I have been googling to help myself but it's challenging to understand how they actually work! I have no code!
Thanx in advance for assisting me and responding to my questions!
0 comentarios
Respuesta aceptada
  Ajay Kumar
      
 el 3 de Oct. de 2019
        
      Editada: Ajay Kumar
      
 el 3 de Oct. de 2019
  
      First try to understand the sorting algorithm. There are many videos on youtube that explains bubble sort.
Your data being x.
num = numel(x);
for j = 0 : num-1
    for i = 1: num-j-1
        if x(i)>x(i+1)
            temp = x(i);
            x(i) = x(i+1);
            x(i+1) = temp;
        end
    end
end
7 comentarios
  Rik
      
      
 el 4 de Oct. de 2019
				This code has nothing to do with your question. The sort function doesn't use bubble sort, because there are much more efficient algorithms for sorting.
  Guillaume
      
      
 el 4 de Oct. de 2019
				Indeed what has that code to do with the initial question?
Note that in each of the proposed code it would be more efficient to stop as soon as the inner loop has done a pass without any swapping, rather than continue scanning the whole array.
"I was of the opinion that the for loop was the solution"
There's not much difference between a for loop and a while loop. That was my point to Kumar. You can always rewrite a for loop as a while loop and vice-versa
for i = 1:10
    %do something
end
is equivalent to:
i = 1;
while i <= 10
    %do something
    i = i+1;
end
while:
while somecondition
    %do something
end
is equivalent to
for i = 1:Inf
    if somecondition
        break;
    end
    %do something
end
Más respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

