开始Java:排序方法说明
这是一个排序方法的示例:开始Java:排序方法说明,java,Java,这是一个排序方法的示例: int sorting = 0; for(int i = 0; i<myArray.length-1; i++){ for(int s = i+1; s<myArray.length; s++){ if(myArray[i] > myArray[s]){ sorting = myArray[i]; myArray[i] = myArr
int sorting = 0;
for(int i = 0; i<myArray.length-1; i++){
for(int s = i+1; s<myArray.length; s++){
if(myArray[i] > myArray[s]){
sorting = myArray[i];
myArray[i] = myArray[s];
myArray[s] = sorting;
}
}
}
int排序=0;
对于(inti=0;i也许这个解释有帮助
循环不变量:直到i-1的元素被排序,从i到所有
大于或等于
/“将对小于等于-1(=无)的元素进行排序,从0开始,所有元素都大于或等于”
for(int i=0;imyArray[s]){//如果有一个较小的
//在i和s处交换元素:
int oldValueAtI=myArray[i];
myArray[i]=myArray[s];
myArray[s]=oldValueAtI;
}
}
//对于s>i,myArray[i]是最小的
//到i的元素被排序,从i+1开始都大于或等于
}
//对长度小于等于s.length-1的元素进行排序,
//从s.length(=无)开始,所有长度都大于或等于
//所有元素都已排序
因此,您甚至可以简化工作,减少交换:
for (int i = 0; i < myArray.length-1; i++){
// Search the smallest in the rest:
int smallestS = i;
for (int s = i+1; s < myArray.length; s++) {
if (myArray[s] < myArray[smallestS]) {
smallestS = s;
}
}
// Swap the elements at i and smallestS
if (smallestS != i) { // Check not needed
int oldValueAtI = myArray[i];
myArray[i] = myArray[smallestS];
myArray[smallestS] = oldValueAtI;
}
}
for(int i=0;i
从这里看起来像是冒泡排序。非常低效的排序。任何进一步的细化都会复制算法书或维基百科,真的。是的,我现在是初学者,所以我并不真正关心事情的效率。只有它的工作方式,我才知道它为什么会这样。有人能解释吗?Makoto是正确的是你可以通过简单的谷歌搜索轻松找到的东西
// "The elements upto -1 (=none) are sorted, from 0 are all greater or equal"
for (int i = 0; i < myArray.length-1; i++){
// The elements upto i-1 are sorted, from i are all greater or equal
for (int s = i+1; s < myArray.length; s++) { // For the elements after i
if (myArray[i] > myArray[s]) { // If there is a smaller one
// Swap the elements at i and s:
int oldValueAtI = myArray[i];
myArray[i] = myArray[s];
myArray[s] = oldValueAtI;
}
}
// myArray[i] is smallest for s > i
// The elements upto i are sorted, from i+1 are all greater or equal
}
// The elements upto s.length - 1 are sorted,
// from s.length (=none) are all greater or equal
// All elements are sorted
for (int i = 0; i < myArray.length-1; i++){
// Search the smallest in the rest:
int smallestS = i;
for (int s = i+1; s < myArray.length; s++) {
if (myArray[s] < myArray[smallestS]) {
smallestS = s;
}
}
// Swap the elements at i and smallestS
if (smallestS != i) { // Check not needed
int oldValueAtI = myArray[i];
myArray[i] = myArray[smallestS];
myArray[smallestS] = oldValueAtI;
}
}