java - 为什么这个循环排序实现有一个错误?

标签 java algorithm sorting

众所周知的问题:

给定 n 个范围从 1 到 n 的数组。就地排序 O(1) 空间。

Input: [3, 1, 5, 4, 2]
Output: [1, 2, 3, 4, 5]

我的解决方案是

  public static void sort(int[] nums) {
    int n = nums.length;

    for(int i = 0; i < n; i++){
      if(nums[nums[i] -1] != nums[i]){  // if I use while here it works.
        int j = nums[i] -1;
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
      }
   }
 }    

但这有一个错误如下。

Input: [1, 5, 6, 4, 3, 2]
Wrong output: [1, 3, 2, 4, 5, 6]

如果我在 for 循环中使用 while (而不是 if),它就可以工作。 我不明白为什么如果我在 for 循环中使用 if 语句,它会出现错误。

有人可以解释一下原因吗?

最佳答案

如果你不想这样做Arrays.sort(nums)

,这应该可以工作
int[] nums= new int[]{ 1, 5, 6, 4, 3, 2 }; 
int n = nums.length;

for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
    if (nums[i] < nums[j]) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
 }
}
for (int i = 0; i < n; i++){
  System.out.println(nums[i]);
}

输出

[1, 2, 3, 4, 5, 6]

关于java - 为什么这个循环排序实现有一个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649935/

相关文章:

java - 显示猜谜游戏的游戏数、最佳游戏和总尝试次数

java - 如何正确序列化和反序列化 CSV?

c++ - 计算排序字符串的算法(自制软件 "uniq -c")

java - volatile 关键字有什么用?

java - 如何在选择同一 div 中存在的下拉列表时在 div 末尾附加动态生成的 HTML 表格?

algorithm - 在 N x M 矩阵中找到最大邻居数等于它们在最佳时间的邻居数

algorithm - 如何计算 CPU 计算成本与将数据发送到 GPU+执行计算+取回数据的成本?

c++ - 使用迭代器排序列表不会对最后一个元素 C++ 进行排序

java - 使用ES java库准备嵌套排序过滤器

python-2.7 - 在 python 中使用合并排序排列给定的整数列表以获得最少的数字