1

我一直在尝试将冒泡排序算法更改为选择排序,但我很挣扎。

这是冒泡排序...

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]);

谢谢大家,我是编程新手,算法让我明白!

4

1 回答 1

1

这是选择排序的伪代码:

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
于 2012-11-20T07:13:05.060 回答