從明顯
Arrays.sort()方法是這樣
旁白:
import java.util.Arrays;
Arrays.sort(array);
我已經創建了一個插入排序算法的方法來排序的int[]
(中評論來自於我是一名noob程序員)。插入似乎對我和我所有的嘗試都是最快的。
public int[] sort(int[] array) // public static int[] sort(int[] array)
{
int pass = 0, comp = 0; // represents pass as the position, in the array, of the value being inserted; and comp, as the comparison variable, that is the value being inserted.
int temp; // represents a temporary int to assist in switching array values.
for (pass = 1; pass < array.length; pass++) // for every position in the array (except the first element)...
{
comp = pass; // have the comparison/insertion variable be equal to which pass the method is on.
while (comp > 0) // only do this while the comparison/insertion variable position is greater than 0 (because otherwise it wouldn't have any adjacent positions (to the left) left).
if (array[comp] < array[comp - 1]) // if the comparison/insertion value is less than its adjacent position (to the left), swap the values:
{
temp = array[comp]; // set the temporary variable to hold the value of the comparison/insertion variable's value.
array[comp] = array[comp - 1]; // change the comparison/insertion variable's value to be its adjacent positions value.
array[comp - 1] = temp; // set the adjacent positions value to be the temporary variable's value.
comp --; // set the comparison to be backwards 1 to keep checking where it needs to finally be inserted.
}
else // otherwise (if the comparison variable value is greater than or equal to its adjacent position to the left)...
{
break; // exit the do loop to avoid an endless cycle.
}
}
return array;
}
樣品輸入/用途:
public static void main(String[] args)
{
int[] array = {54, 7, 2, 7, 15, 16};
System.out.print(Arrays.toString(sort(array)));
}
[2,7,7,15,16,54]
張貼問題時,不要採取任何快捷方式。 –
分開你的問題。不要;二合一後,它很難回答 – Sinkingpoint
請定義最低複雜度。 'Arrays.sort(a);'非常簡單。另外,你的方式不起作用。你的第二個問題是不完整的,但我想你問什麼是[匿名類](http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)。 –