有人可以解释为什么这个冒泡排序在我的代码中不起作用。我认为这很容易。也许不是所有都正确,但仍然有点排序,但它只是返回相同的数组?
import java.util.Random;
public class Sorts {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Set array to be sorted length here!
int listLength = 20;
//Declares Array
int[] toBeSortedArray = new int[listLength];
int[] sortedArray = new int[listLength];
//fills Array with random numbers
for (int i = 0; i < listLength; i++)
{
Random rand = new Random();
toBeSortedArray[i] = rand.nextInt(100);
}
//Passing toBeSortedArray to function
sortedArray = SwapSort(toBeSortedArray, listLength);
//Testing the filling of Array - *hint* select all comment lines and select "Toggle Block Comment"
for (int i = 0; i <listLength; i++)
{
System.out.print(toBeSortedArray[i] + ", ");
}
System.out.println();
for (int i = 0; i <listLength; i++)
{
System.out.print(sortedArray[i] + ", ");
}
}
public static int[] SwapSort(int[] array, int length)
{
int temp;
for (int i = 0; i < length; i++)
{
for (int j = 1; j < length - 1; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j+1];
array[j+1] = temp;
}
}
}
return array;
}
}
输出:
55, 42, 50, 48, 9, 38, 84, 10, 81, 24, 5, 18, 32, 74, 2, 89, 15, 84, 84, 45,
55, 42, 50, 48, 9, 38, 84, 10, 81, 24, 5, 18, 32, 74, 2, 89, 15, 84, 84, 45,
答案 0 :(得分:2)
三件事
首先,您正在交换错误的元素。
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
您必须交换元素array [i]和array [j]
第二
您的内部循环开始时必须以j = i + 1
而不是1
开头,并且应该最多length
。
<强>第三强>
由于在调用函数后在代码中打印了两个数组,因此两者都会提供相同的输出,因为java通过引用传递数组,并且原始数组也会被修改。因此,即使您的原始代码中发生了交换,您也可以获得相同的输出
完整代码
class Sorts {
public static void main(String[] args) {
//Set array to be sorted length here!
int listLength = 20;
//Declares Array
int[] toBeSortedArray = new int[listLength];
int[] sortedArray = new int[listLength];
//fills Array with random numbers
for (int i = 0; i < listLength; i++) {
Random rand = new Random();
toBeSortedArray[i] = rand.nextInt(100);
}
for (int i = 0; i < listLength; i++) {
System.out.print(toBeSortedArray[i] + ", ");
}
//Passing toBeSortedArray to function
sortedArray = SwapSort(toBeSortedArray, listLength);
}
public static int[] SwapSort(int[] array, int length) {
int temp;
for (int i = 0; i < length; i++) {
for (int j = 1; j < length; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("");
for (int i = 0; i < length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println();
return array;
}
}
答案 1 :(得分:1)
SwapSort
中的内部循环应以int j = i + 1; j < length
(以及外部循环中的i < length - 1
)开头,考虑j
为1
时发生的情况您的算法中i
为2
。此外,您的交换应该在比较的元素上进行。像,
public static int[] SwapSort(int[] array, int length) {
int temp;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
if (array[i] > array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}