7. แถวลำดับ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 7-15  เมท็อดเรียงลำดับข้อมูลในอาเรย์
public class Sorting {
  public static void main(String[] args) {
    double[] data = {9,3,2,4,1,5,6};
    selectionSort(data);
    print(data);
  }
  public static void selectionSort(double[] d) {  
    for (int k=d.length-1; k>0; k--) {
      int maxI = maxIndex(d, 0, k);
      swap(d, maxI, k);
    }
  }
  private static int maxIndex(double[] d, int left, int right) {
    if (left > right) throw new IllegalArgumentException("0 ช่อง");
    int maxI = left;
    for (int i=left+1; i<=right; i++) {
      if (d[i] > d[maxI]) maxI = i;
    }
    return maxI;
  }
  private static void print(double[] d) {
    System.out.print("[");
    for (int i=0; i<d.length; i++) {
      System.out.print(d[i]);
      if (i<d.length-1) System.out.print(",");
    }
    System.out.println("]");
  }
  private static void swap(double[] d, int i, int j) {  
    double t = d[i];
    d[i] = d[j];
    d[j] = t;
  }
}
©2009 S.Prasitjutrakul