gpt4 book ai didi

java - for循环中的后缀和前缀

转载 作者:行者123 更新时间:2023-11-29 08:50:46 24 4
gpt4 key购买 nike

我遇到了这些用于排序的示例,我对这里的后缀和前缀感到很困惑——为什么最后使用了——但这里使用了++currIndex?在第二个例子中它只使用了++pass 和++index?这些在排序中重要吗?非常感谢!

for (int last = n-1; last >= 1; last--) {
int largest = indexOfLargest(theArray, last+1);
int temp = theArray[largest];
swap theArray[largest] = theArray[last];
theArray[last] = temp;
}

private static int indexOfLargest(int[] theArray, int size) {
int indexSoFar = 0;
for (int currIndex = 1; currIndex < size; ++currIndex) {
if (theArray[currIndex]>theArray[indexSoFar])
indexSoFar = currIndex;
}
return indexSoFar;

示例 2:

for (int pass = 1; (pass < n) && !sorted; ++pass) {
sorted = true;
for (int index = 0; index < n-pass; ++index) {
int nextIndex = index + 1;
if (theArray[index]>theArray[nextIndex]) {
int temp = theArray[index];
theArray[index] = theArray[nextIndex];
theArray[nextIndex] = temp;
}

最佳答案

简单来说,不影响排序。这是您关于如何执行递增/递减的合乎逻辑的决定

例如

int i = 0;

while (something) { //any loop for/while
array[++i] = some data; //increment i first and then next do operation
}

is similar to

int i = 1;
while (something) {
array[i++] = some data; //do operation and then increment
}

但重要的区别是++i先执行,然后根据i执行你想执行的操作。另一种情况是先对 i 进行运算,再进行自增

关于java - for循环中的后缀和前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837265/

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