selectionsort.java
来自「此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码」· Java 代码 · 共 61 行
JAVA
61 行
// SelectionSort.java: Sort numbers using selection sort
public class SelectionSort
{
// Main method
public static void main(String[] args)
{
// Initialize the list
double[] myList = {5.0, 4.4, 1.9, 2.9, 3.4, 3.5};
// Print the original list
System.out.println("My list before sort is: ");
printList(myList);
// Sort the list
selectionSort(myList);
// Print the sorted list
System.out.println();
System.out.println("My list after sort is: ");
printList(myList);
}
// The method for printing numbers
static void printList(double[] list)
{
for (int i=0; i<list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
// The method for sorting the numbers
static void selectionSort(double[] list)
{
double currentMax;
int currentMaxIndex;
for (int i=list.length-1; i>=1; i--)
{
// Find the maximum in the list[0..i]
currentMax = list[i];
currentMaxIndex = i;
for (int j=i-1; j>=0; j--)
{
if (currentMax < list[j])
{
currentMax = list[j];
currentMaxIndex = j;
}
}
// Swap list[i] with list[currentMaxIndex] if necessary;
if (currentMaxIndex != i)
{
list[currentMaxIndex] = list[i];
list[i] = currentMax;
}
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?