java实现冒泡选择二分排序_java 实现简单排序(冒泡,选择,插入)

package helloclean.basetest;

/**

* 简单排序: 冒泡,选择,插入 排序

*/

public class ArrayBub {

private long[] a;

private int nElems;

public ArrayBub(int max) {

a = new long[max];

nElems = 0;

}

public void insert(long value) {

a[nElems] = value;

nElems ++;

}

public void disPlay() {

for(int i = 0; i < nElems; i ++) {

System.out.print(a[i] + " ");

}

System.out.println();

}

//冒泡排序

public void bubbleSort() {

int out, in;

for(out = nElems -1; out > 0; out --) {

for(in = 0; in < out; in ++) {

if(a[in] > a[in + 1]) {

swap (in,in + 1);

}

}

}

}

//选择排序

public void selectionSort() {

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 insertionSort() {

int in,out;

for(out = 1; out < nElems; out ++) {

long temp = a[out];

in = out;

while (in > 0 && a[in - 1] >= temp) {

a[in] = a[in -1];

-- in;

}

a[in] = temp;

}

}

/**

* 二分查找,返回下标,如果没有找到,返回数组的长度

* @param key

* @return

*/

public int find(long key) {

int lowBound = 0;

int highBound = nElems -1;

int curIn;

while (true) {

curIn = (lowBound + highBound) / 2;

if(a[curIn] == key) {

System.out.println("找到数据 " + key + " 其下标为: " + curIn);

return curIn;

} else if (lowBound > highBound) {

System.out.println("没有找到数据,返回数组的长度: " + nElems);

return nElems;

} else {

if(a[curIn] < key) {

lowBound = curIn + 1;

} else {

highBound = curIn -1;

}

}

}

}

private void swap(int x, int y) {

long temp = a[x];

a[x] = a[y];

a[y] = temp;

}

public static void main(String[] args) {

int maxSize = 100;

ArrayBub arrayBub = new ArrayBub(maxSize);

arrayBub.insert(100);

arrayBub.insert(1);

arrayBub.insert(50);

arrayBub.insert(40);

arrayBub.insert(10);

arrayBub.insert(60);

arrayBub.insert(70);

arrayBub.disPlay();

// arrayBub.bubbleSort();

// arrayBub.selectionSort();

arrayBub.insertionSort();

arrayBub.disPlay();

arrayBub.find(70);

arrayBub.find(90);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值