selectionsort.java

来自「这是Java的模式编程」· Java 代码 · 共 40 行

JAVA
40
字号
package Strategy;
import java.lang.Comparable;

public class SelectionSort extends SortStrategy
{
   /** sort the array a using the selection sort method */
   private void swap(Comparable [] a, int i, int j)
   {
      Comparable temp = a[i];
      a[i] = a[j];
      a[j] = temp;
   }
       
   private int max(Comparable [] a, int n)
   {
      if (n < 0)
         throw new IllegalArgumentException
               ("MyMath.max: Cannot find max of zero elements ");

      int positionOfCurrentMax = 0;
      for (int i = 1; i <= n; i++)
         if (a[positionOfCurrentMax].compareTo(a[i])<0)
            positionOfCurrentMax = i;
      return positionOfCurrentMax;
   }
   
   public void sort(Comparable [] a)
   {
      for (int size = a.length; size > 1; size--)
      {
         // find max object in a[0:size-1]
         int j = max(a, size-1);

         // move max object to right end
         swap(a, j, size - 1);
      }
      super.printArray(a);
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?