文档库

最新最全的文档下载
当前位置:文档库 > java选择排序

java选择排序

package choice;

/**

* 选择排序

* @author Administrator

*

*/

public class ChoiceSort {

public static void main(String[] args) {

int[] a = new int[] { 9, 6, 4, 2, 1, 3, 5, 8, 7 }; System.out.println("before sort...");

printArray(a);

choiceSort(a);

System.out.println("after sort...");

printArray(a);

}

private static void choiceSort(int[] a) {

for (int i = 0; i < a.length; i++) {

int temp = a[i];

int index = i;

for (int j = i + 1; j < a.length; j++) {

if (temp > a[j]) {

temp = a[j];

index = j;

}

}

a[index] = a[i];

a[i] = temp;

}

}

public static void printArray(int[] a) {

for (int i = 0; i < a.length; i++) {

System.out.print(a[i] + " ");

}

System.out.println();

}

}