如何将冒泡排序算法更改为选择排序?

时间:2012-11-08 11:39:42

标签: pseudocode

我一直试图将我的bubblesort算法改为选择排序,但我正在努力。

这是泡泡排序......

For K= 0 to n – 2 
For j = 0 to n – k - 2
If item[j] > item [j + 1]
temp = item[j]
item[j] = item[j+1]
item[j + 1] = temp
end if
end for 
end for
end bubbleSort

这是朋友用javascript给我的东西,我想知道是否有人可以帮助将其变成伪代码?谢谢......

var arr = new Array(23, 19, 35, 12, 30);
temp = 0;

for (k = 0; k < arr.length - 1; k++) {

for (j = k + 1; j < arr.length; j++) {

if (arr[k] > arr[j]) {

temp = arr[k];
arr[k] = arr[j];
arr[j] = temp;
}
}
}

for (k = 0; k < arr.length; k++)
alert(arr[k]);

谢谢大家,我是编程和算法的新手,只需要我!

1 个答案:

答案 0 :(得分:0)

这是一个选择排序的伪代码:

A = array(23, 19, 35, 12, 30) // make an array
n = length(A)                 // array length
min = 0                       // minimum element index is 0

for j = 0 to n - 1 do         // go through array
   min = j                    // assume the minimum element is the first element

   for i = j + 1 to n do      // test elements behind j-th element
      if(A[i] < A[min]) then  // if any of those elements is smaller, it's the new minimum
         min = i
   end for

   if(min <> j) then          // swap the minimum element (min) with the current (j)
      tmp = A[j]
      A[j] = A[min]
      A[min] = tmp
end for