这篇是选择排序算法!为了练习和巩固以前的知识!
代码如下:
class ArraySel
{
private long[] a;
private int nElems;
public ArraySel(int maxSize){
a = new long[maxSize];
nElems = 0;
}
public void insert(long value){
a[nElems] = value;
nElems++;
}
public boolean find(long searchKey){
int j;
for(j = 0;j < nElems;j++){
if(a[j] == searchKey){
break;
}
}
if(j == nElems){
return false;
}else{
return true;
}
}
public boolean delete(long value){
int j;
for(j = 0;j < nElems;j++){
if(a[j] == value)
break;
}
if(j == nElems){
return false;
}else{
for(int k = j; k < nElems;k++)
a[k] = a[k + 1];
nElems--;
return true;
}
}
public void display(){
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;out++){
min = out;
for(in = out + 1;in < nElems;in++)
if(a[in] < a[min])
min = in;
swap(out,min);
}
}
//选择排序中之逆序排序输出
public void selectSort2(){
int out2,in2,max;
for(out2 = 0;out2 < nElems;out2++){
max = out2;
for(in2 = out2 + 1;in2 < nElems;in2++)
if(a[in2] > a[max])
max = in2;
swap(out2,max);
}
}
private void swap(int x,int y){
long temp = a[x];
a[x] = a[y];
a[y] = temp;
}
}
public class SelectSortApp
{
public static void main(String[] args){
int maxSize = 100;
ArraySel arr;
arr = new ArraySel(maxSize);
arr.insert(77);
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);
arr.display();
arr.selectSort();
arr.display();
arr.selectSort2();
arr.display();
System.out.println("############################");
int searchKey = 35;
if(arr.find(searchKey)){
System.out.println("Found "+ searchKey);
}else{
System.out.println("Can't find " + searchKey);
}
arr.delete(00);
arr.delete(99);
arr.display();
arr.selectSort();
arr.display();
arr.selectSort2();
arr.display();
System.out.println("############################");
arr.insert(00);
arr.insert(99);
arr.display();
arr.selectSort();
arr.display();
arr.selectSort2();
arr.display();
}
}
运行结果如图所示: