Bubble sort for loop
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
0 개 추천
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!
채택된 답변
Ajay Kumar
2019년 10월 3일
편집: Ajay Kumar
2019년 10월 3일
3 개 추천
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
Guillaume
2019년 10월 3일
Also, 2 for loops are not required for bubble sorting.
Well, you'ver replaced one of the for loop by a while loop. for and while loops are more or less equivalent. You can always rewrite one in term of the other.
However, note that your algorithm does not work properly (the while condition is very incorrect). E.g it will fail to sort properly
x = [1 3 2]
%or
x = [3 1 4 2]
Ajay Kumar
2019년 10월 3일
Corrected. Thanks.
Matpar
2019년 10월 4일
Ok guys,
I was of the opinion that the for loop was the solution! now i am confused with the while loop!
please guide me!
thanks in advance!
Rik
2019년 10월 4일
Then look at the edited answer.
The point of bubble sort is to loop through all elements. For each element look at all remaining elements on one side and swap them if necessary. I find it more intuitive to loop from 1, so like the code below. (written on mobile, untested)
for n=1:(numel(x)-1)
for m=(n+1):numel(x)
if x(m) > x(n)
x([n m])=x([m n]);
end
end
end
Matpar
2019년 10월 4일
forgive me I tired and well I am still here trying I manage to get the understnding going via the manaual way!
This is where i've gotten;
%% Exhaustive Search Implementation
%Imaginative Points Specified on the X Y plane of 2 dimensional Image
% Point W,X,Y,Z, the distance between W & Y as well as Z & W
w=[4,9]; %
x=[1,5]; %
y=[7,2]; %
z=[3,5]; %
wy=[11,3];
zw=[4,1];
%% Specified the distance of each point utilising the Euclidean Distance
%euclideanDistance = sqrt((w2-w1)^2+(x2-x1)^2+(y2-y1)^2+(z2-z1)^2);
%w>x>y>z>xz>wy
ed_wxyz = sqrt((9-4)^2+(5-1)^2 +(2-7)^2+(5-3)^2+(3-11)^2+(1-4)^2);
%% Specified Each Point Individually For Cross Validation Purposes
edw_x = sqrt((9-4)^2+(5-1)^2);
edx_y = sqrt((5-1)^2+(2-7)^2);
edy_z = sqrt((2-7)^2+(5-3)^2);
edz_w = sqrt((5-3)^2+(9-4)^2);
edx_z = sqrt((5-1)^2+(5-3)^2);
edw_y = sqrt((9-4)^2+(2-7)^2);
%% Created Variable T to Sort All Point In Descending Order
t = [edw_x,edx_y,edy_z,edz_w,edx_z,edw_y,ed_wxyz];
sortpoints = sort(t,'descend');
%% Display All Point Individually
disp('The Euclidean Distance of the points are=>');
disp('edw_x'); disp(edw_x);
disp('edx_y'); disp(edx_y);
disp('edy_z'); disp(edy_z);
disp('edz_w'); disp(edz_w);
disp('edx_z'); disp(edx_z);
disp('edw_y'); disp(edw_y);
disp('edw_x'); disp(ed_wxyz);
disp('Here are the points in **RANDOM** order');
%% Display Sorted Points In Descending Order From Matlab Built-in Sort Fucntion
disp(t);
disp('Here are the points in **DESCENDING** order');
%%
% *************************************************************************************
disp(sortpoints);
%%
% *************************************************************************************
disp('This point (X_Z) is the lowest calculation=> 4.4721')
Rik
2019년 10월 4일
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
2019년 10월 4일
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
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
