gpt4 book ai didi

sorting - 如何在smalltalk中制作排序方法

转载 作者:行者123 更新时间:2023-12-04 22:11:25 24 4
gpt4 key购买 nike

我正在尝试在 smalltalk 中创建一种新的排序方法。任何人都知道如何将此排序Java代码更改为吱吱声?

public static void SelectionSort ( int [ ] num )
{
int i, j, first, temp;
for ( i = num.length - 1; i > 0; i - - )
{
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
if( num[j] < num[first] )
first = j;
}
temp = num[first]; //swap smallest found with element in position i.
num[first] = num[ i ];
num[i] = temp;
}
}

最佳答案

这是一行一行的翻译。行号不是代码的一部分。

 1. selectionSort: num
2. | first temp |
3. num size to: 1 by: -1 do: [:i |
4. first := 1. "initialize to subscript of first element"
5. 1 to: i do: [:j |
6. "locate smallest element between positions 1 and i"
7. (num at: j) < (num at: first) ifTrue: [first := j]].
8. temp := num at: first. "swap smallest with element in position i"
9. num at: first put: (num at: i).
10. num at: i put: temp]

备注:
  • 无参数类型声明。没有答案类型。
  • 在块内声明的临时块 ij(第 3 行和第 5 行)。在 Smalltalk 中,索引集合是基于 1 的。
  • num.length() -> num size 。减少 for 循环转化为 to:by:do: 消息。
  • 赋值 = 变成 :=0 变成 1(见上面的注释 2。)
  • 增加 for 循环转化为 to:do: 消息。
  • 注释用双引号括起来。
  • [j] 转换为 at: j 消息。 if 转换为 ifTrue: 消息。
  • temp 可以在第一个块中声明: do: [:i | | temp |...
  • num[j] = temp 也成为发送 at:put: 的消息。
  • 同上 9. 另请注意,您可以对第 9 行和第 10 行使用级联语法:
    num
    at: first put: (num at: i);
    at: i put: temp
  • 不需要回答num,因为它已经被方法修改了。然而,请看,有趣的讨论起源于 Amos 的回答: Why shouldn't I store into literal arrays in Smalltalk?
  • 关于sorting - 如何在smalltalk中制作排序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29958850/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com