0
点赞
收藏
分享

微信扫一扫

数据结构与算法——简单排序


public class Sort {

//存值数组
private int[] a;
//数组实际大小
private int nElems;

public Sort(int max) {
a=new int[max];
nElems=0;
}

public void insert(int value) {
a[nElems]=value;
nElems++;
}

//冒泡排序
public void bubbleSort() {

for (int out = nElems-1; out>1; out--) {
for(int in=0;in<out;in++)
{
if (a[in]>a[in+1]) {
swap(in,in+1);
}
}

}
}

//选择排序
public void selcetSort() {
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);
}
}
}
}

//插入排序
public void insertSort() {
int in,out;
for(out=1;out<nElems;out++)
{
int temp=a[out];
in=out;
while (in>0&&a[in-1]>temp)
{
a[in]=a[in-1];
--in;
}
a[in]=temp;
}
}
private void swap(int one,int two) {

int temp=a[one];
a[one]=a[two];
a[two]=temp;
}

public void disply() {
for (int i = 0; i < nElems; i++) {
System.out.println(a[i]+" ");
}
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Sort sort=new Sort(100);
sort.insert(12);
sort.insert(34);
sort.insert(1);
sort.insert(6);
sort.insert(7);
sort.insert(65);

// sort.bubbleSort();
// sort.disply();
// sort.selcetSort();
// sort.disply();
sort.insertSort();
sort.disply();
}


举报

相关推荐

0 条评论