Can someone help me understand bubble sort.

30 ビュー (過去 30 日間)
Hussain Hayat
Hussain Hayat 2015 年 8 月 2 日
コメント済み: Katlyn Rivera 2022 年 2 月 17 日
I cant understand bubble sort(the code is given above). How is j and k used. In the for loop why is [ j = 1 : n-k ]. What does fewer tests on each pass mean. And I cant understand how temp is used to switch two numbers in x. And why is sorter reset to 0 after each for loop. Can someone explain this part by part? I only get the basic idea of how two numbers are compared and then replaced (or not) but how is it checked. Which two numbers are chosen first?
  1 件のコメント
Katlyn Rivera
Katlyn Rivera 2022 年 2 月 17 日
its actually swap not swop

サインインしてコメントする。

採用された回答

Geoff Hayes
Geoff Hayes 2015 年 8 月 2 日
Hussain - given the condition
x(j) > x(j+1)
the list is being sorted in ascending order (since the subsequent code replaces the j+1 element with the j element). Since k is initialized to zero, then when we enter the while loop, k is incremented by one (and so is set to one) and we then iterate over j from 1 to n-k or the length of the list less one as
k = k + 1;
for j = 1:n-k
So if the list is of size 10, j iterates from one to nine. We then compare the two neighbouring elements as
if x(j) > x(j+1)
trying to determine if the element at position j is greater than the element at position j+1. If this is true, and since we are sorting the list in ascending order, then we need to swap these two elements which we do with
temp = x(j);
x(j) = x(j+1);
x(j+1) = temp;
The idea is that we want to "push" the largest elements to the end of the list. We then set the sorted flag to zero and move on to the second iteration of the for loop. Note that we continue in this manner until we have iterated over each element and have pushed the largest element (of the list) to the end. If sorted is zero, then we repeat and increment k by one which means it is now 2. Since j iterates from 1:n-k then with k being two we iterate from one to eight (and so the comment fewer tests on each pass makes sense.
In order to better understand what the code is doing you should try it with a simple example and step through the code, line by line, to see how the list is being manipulated on each iteration. See http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/ for details on how to debug.
  1 件のコメント
Hussain Hayat
Hussain Hayat 2015 年 8 月 3 日
Just what I was looking for.Very well explained, thanks a lot. :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by