Java中数组的排序方法的实现方式


package date0609;

/**
*@author TonyJ
*@time 2011-6-9 下午05:45:16
*/
public class Test02 {
private long[] a;
private int nElems;

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

public int size() {
return nElems;
}

public void add(long data) {
a[nElems++] = data;
}

public int find(long desData) {//二分查找
int low = 0;
int high = nElems - 1;
int cur;
while (true) {
cur = (low + high) / 2;
if (a[cur] == desData) {
return cur;
} else if (low > high) {
return -1;
} else {
if (a[cur] < desData) {
low = cur + 1;
} else {
high = cur - 1;
}
}
}
}

public long get(int index) { //根据下标取得数组的值
if (index > nElems) {
System.out.print("无效下标");
return -1;
} else {
return a[index];
}
}

public boolean delete(long desData) {//删除操作
int j = find(desData);
if (j == -1) {
return false;
} else {
for (int i = j; i < nElems - 1; i++) {
a[i] = a[i + 1];
}
nElems--;
return true;
}
}

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

public void bubbleSort() {//冒泡排序
for (int i = 1; i < nElems; i++) {
for (int j = 0; j < nElems; j++) {
if (a[i] < a[j]) {
swap(i, j);
}
}
}
}

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);
}
}

public void insertSort() {//插入排序
int out, in;
long temp;
for (out = 1; out < nElems; out++) {
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) {
long temp;
temp = a[one];
a[one] = a[two];
a[two] = temp;
}

public static void main(String[] args) {
Test02 t = new Test02(6);
t.add(3);
t.add(4);
t.add(5);
t.add(1);
t.add(2);
t.add(6);
t.insertSort();
System.out.println(t.get(4));
System.out.println(t.find(2));
// t.bubbleSort();
// t.selectSort();
t.display();
t.delete(3);
t.display();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值