欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-24 12:05:04
...
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();
	}
}

相关标签: Java J#