二.选择排序法的java实现
冒泡,选择,插入排序是最基本的也是有效的排序方式,这里主要用java编写了选择排序的实现,其中的思想在ArraySel.classs的selectionSort()方法中。
- //selectArray.java
- //demonstrates selection sort
- /
- public class ArraySel {
- private long[]a;//ref to array a
- private int nElems;//number of array data items
- //---------------------------------------------------
- public ArraySel(int max)//construtor
- {
- a=new long[max];//creat the array,declaration
- nElems=0;//there is no items yet
- }
- //...................................................
- public boolean find(long searchKey)//find the specified value
- {
- int j;
- for(j=0;j<nElems;j++)
- {
- if(a[j]==searchKey)
- break;//found it and jump out of the loop
- }
- if (j==nElems)return false;//not found
- else return true;
- }
- //...................................................
- public void insert(long value)//put element into array
- {
- a[nElems]=value;//put the value into the array
- nElems++;//add the total number of the data items
- }
- public boolean delete(long value)//delete an array item
- {
- int j,k;
- for(j=0;j<nElems;j++)//search the item
- {
- if(a[j]==value)
- break;
- }
- if(j==nElems)return false;//not found
- else
- {
- for(k=j;k<nElems;k++)//put every item behind the target one ahead
- {
- a[k]=a[k+1];
- }
- nElems--;
- return true;
- }
- }
- public void selectionSort()
- {
- int out,in,min;
- long temp;
- for(out=0;out<nElems-1;out++)//outer loop
- {
- min=out; //minimum
- for(in=out+1;in<nElems;in++)//inner loop
- if(a[in]<a[min])min=in;//if min greater
- temp=a[min];
- a[min]=a[out]; //replace the first inner place with min
- a[out]=temp;
- }
- }
-
- //....................................................
- public void insertionSort()
- {
- int in,out;
- for(out=1;out<nElems;out++)//the out loop
- {
- long temp=a[out];//remove marked item
- for(in=out;in>0;in--)//start inner loop at out
- { //until one is smaller
- if(a[in-1]>temp)
- a[in]=a[in-1];//when not met,shift item right
- else break;//when met,jump out
- }
- a[in]=temp; //insert the flag into a[in],the proper position
- }
- }
- //......................................................
- public void display()
- {
- for(int j=0;j<nElems;j++)
- {
- System.out.println(a[j]+" ");
- }
- //....................................................................
- }
- }
主函数调用
- public class ArraySelApp {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- 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(16);
- arr.insert(33);
- arr.insert(56);
- arr.insert(33);
- arr.display(); //display items
- System.out.println();
- System.out.println();
- arr.selectionSort();
- arr.display();
- }
- }
结果输出
- 77
- 99
- 44
- 55
- 22
- 16
- 33
- 56
- 33
- 16
- 22
- 33
- 33
- 44
- 55
- 56
- 77
- 99