誰かがこのバブルの並べ替えが私のコードでうまくいかない理由を説明することはできますか?私はこれが簡単に並べ替えると思います。たぶんすべて正しくはないがまだ幾分ソートされているのではなく、代わりに同じ配列を返しますか?Bubble Sortは同じ配列を再び返しますか?
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;
}
}
出力:j
は1
で、i
は、あなたの中に2
とき
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,
:あなたは、配列を変更しています渡されたので、入力を変更しています。そしてあなたのアルゴリズムは壊れています。しかし、あなたのアルゴリズムが働いていれば、それらは同じであるが、ソートされています。 –