Understanding Bubble Sort Algorithms

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 3K views
Juanka
Messages
37
Reaction score
0
Anyone familiar with a bubble sort? and if so how to implement it?
 
Physics news on Phys.org
I have two array of numbers an x array and a y array. I want to sort the y array to find the minimum y value, but the number I am looking for is the corresponding x value. I do not know how to sort just the y array allowing each respective x value to remain with each y value. I tried building a matrix [x y] and sorting it but obviously it sorted both arrays. Comments Please.
 
Start with the procedure for sorting the y array and make sure that it works properly.

Then, wherever you swap two y values, add code that also swaps the corresponding x values. For example, if you are swapping the values in positions i and j:

temp = y;
y = y[j];
y[j] = temp;

temp = x;
x = x[j];
x[j] = temp;

If you sort the y values in ascending order, the first item in the x array after the sort has finished, is the one you want.
 
I tried adding the code you gave me into the bubble sort i have, however I am having a problem. Why does this not work?

Code:
function y= bubble(x,y) 
n = length(x); 
for k = 1:n-1 
  for j = 1:n-k 
   if(x(j)> x(j+1)) 
    temp = x(j); 
    x(j) = x(j+1); 
    x(j+1) = temp; 
   
   temp = y(j);
   y(j) = y(j+1);
   y(j+1) = temp;
    
    
   end % if 
  end % for 
end % for 
y = x;
 
Juanka said:
I am having a problem

According to the description in post #3, you want to sort the y array. Therefore in your "if" statement you should be comparing two y values, not two x values. Could that be your problem?
 
Last edited: