package boke.sort;
/**
* 选择排序
*
* @since jdk1.5及其以上
* @author 毛正吉
* @version 1.0
* @date 2010.05.24
*
*/
public class SelectSort {
/**
* @param args
*/
public static void main(String[] args) {
int maxSize = 100;
SelectSort bs = new SelectSort(maxSize);
bs.insert(77);
bs.insert(66);
bs.insert(22);
bs.insert(99);
bs.insert(85);
bs.insert(37);
bs.insert(75);
bs.insert(64);
bs.insert(15);
bs.insert(35);
bs.output(); // 原始输出
bs.selectSort(); // 排序
bs.output(); // 排序输出
}
private long[] a; // 整型数据容器
private int nElems; // 元素个数
/**
* 构造方法
*
* @param maxSize
*/
public SelectSort(int maxSize) {
a = new long[maxSize];
nElems = 0;
}
/**
* 容器放入数据
*
* @param value
*/
public void insert(long value) {
a[nElems++] = value;
}
/**
* 输出容器数据
*/
public void output() {
for (int j = 0; j < nElems; j++) {
System.out.print(a[j] + " ");
}
System.out.println("");
}
/**
* 选择排序
*/
public void selectSort() {
int out, in, min;
for (out = 0; out < nElems - 1; out++) {
min = out;
for (in = out + 1; in < nElems; in++) {
if (a[in] < a[min]) {
min = in;
}
}
swap(out, min);
}
}
/**
* 交换
*
* @param in
* @param i
*/
private void swap(int one, int two) {
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
}
Java选择排序代码整理
最新推荐文章于 2024-05-19 15:19:11 发布