简体   繁体   English

冒泡排序功能不对给定数组进行排序

[英]Bubble sort function does not sort the given array

So basically, I have set up bubblesort algorithm and weirdly enough it does not return the sorted array just the unsorted array. 所以基本上,我已经设置了bubblesort算法,奇怪的是它没有返回排序数组只是未排序的数组。

The given array; 给定的数组;

int[] array = { 20, 5, 1, 6, 23, 52, 15, 12 };

Bubble sort algorithm; 冒泡排序算法;

public static int[] sort_array(int[] array) {

    int [] sorted = array;
    int temp = 0;

    for (int i = 0; i < sorted.length - 1; i++) {
        for (int j = 0; i < sorted.length - i - 1; i++) {
            if (sorted[j] > sorted[j + 1]) {
                temp = sorted[j];
                sorted[j] = sorted[j + 1];
                sorted[j + 1] = temp;
            }
        }
    }
    return sorted;
}

Also made an array return method; 还做了一个数组返回方法;

public static void return_list(int[] array) {

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
}

After the methods are used it just returns me the unsorted array. 使用这些方法后,它只返回未排序的数组。

int[] array = { 20, 5, 1, 6, 23, 52, 15, 12 };

sort_array(array);

return_list(array);

Output = 20, 5, 1, 6, 23, 52, 15, 12; 输出= 20,5,1,6,23,52,15,12;

Duplicating an array (assuming you want to keep the original one) 复制数组(假设您要保留原始数组)

First, you're not copying array into sorted here. 首先,你不是要将array复制到这里sorted You're copying a reference of array to sorted, so any change to the contents of sorted will also be seen in array 你复制阵列的参考排序,所以内容有任何改变sorted也将看到array

int [] sorted = array;

Do this to instantiate a new array sorted and copy contents from array into it: Make copy of array 这样做是为了实例化一个新的数组sorted和复制从内容array进去: 让阵列的复制

There are several ways (Arrays.copyOf, clone, etc.) to do an array copy. 有几种方法(Arrays.copyOf,clone等)来进行数组复制。 For example: 例如:

int[] sorted = Arrays.copyOf(array, array.length);

Sorting bug 排序错误

Also, it looks like there may be a bug in your for loops. 此外,您的for循环中可能存在错误。 You're not iterating through j in this line 你不是在这行中迭代j

for (int j = 0; i < sorted.length - i - 1; i++)

So, the reason it looks like you're getting an unsorted array is that the array isn't being sorted correctly. 所以,看起来你得到一个未排序的数组的原因是数组没有正确排序。

您每次都在检查i的值,并在每次迭代时增加它的值

for (int j = 0; i < sorted.length - i - 1; i++)

有一个错误:在这里用j替换i - > for(int j = 0; i(这里)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM