Understanding Bubble Sort Algorithms

AI Thread Summary
The discussion centers around the implementation of the bubble sort algorithm, particularly in relation to sorting two arrays, x and y, while maintaining their correspondence. Users share resources for learning bubble sort in various programming languages, including MATLAB, C++, Python, and Fortran. A specific issue arises when trying to sort the y array to find its minimum value while keeping the corresponding x values intact. The solution involves modifying the bubble sort algorithm to ensure that when y values are swapped, the corresponding x values are also swapped. A code snippet is provided to illustrate this process. However, a user encounters a problem because they mistakenly compare values from the x array instead of the y array during the sorting process. The key takeaway is to ensure that the sorting condition in the bubble sort algorithm is based on the y values to achieve the desired outcome.
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:
Back
Top