温故而知新之简单排序算法

来源:互联网 发布:匡恩网络校园招聘 编辑:程序博客网 时间:2024/06/05 17:38
package com.ccl.algo;public class SimpleSort {/** * 假设有N个数据需要排序,则从第0个数开始,依次比较第0和第1个数据,如果第0个大于第1个则两者交换,否则什么动作都不做,继续比较第1个第2个…, * 这样依次类推,直至所有数据都“冒泡”到数据顶上。 */public int[] array = new int[] { 109, 12, 3, 543, 1, 29, 17, 487, 98, 432,29, -1, 8 };public void bubbleSort() {for (int i = 0; i < array.length - 1; i++) {for (int j = i + 1; j < array.length; j++)if (array[i] > array[j]) {swap(i, j);}}}/** * 假设有N条数据,则暂且标记第0个数据为MIN(最小),使用OUT标记最左边未排序的数据,然后使用IN标记第1个数据,依次与MIN进行比较, * 如果比MIN小,则将该数据标记为MIN,当第一轮比较完后,最终的MIN与OUT标记数据交换,依次类推; */public void selectSort() {int min, out, in;for (out = 0; out < array.length - 1; out++) {min = out;for (in = out + 1; in < array.length; in++)if (array[min] > array[in])min = in;swap(out, min);}}/** * 插入排序是在部分数据有序的情况下,使用OUT标记第一个无序的数据,将其提取保存到一个中间变量temp中去,使用IN标记空位置, * 依次比较temp中的值与IN‐1的值,如果IN‐值大于temp的值,则后移,直到遇到第一个比temp小的值,在其下一个位置插入 */public void insertionSort() {int out, in, temp;for (out = 1; out < array.length; out++) {temp = array[out];in = out;while (in > 0 && array[in - 1] > temp) {array[in] = array[in - 1];in--;}array[in] = temp;}}/** * @throws no *             idea */public void insertIntosort() {int tail;for (tail = array.length - 1; tail > 0; tail--) {}}public void swap(int i, int j) {int temp = array[i];array[i] = array[j];array[j] = temp;}/** * 逆序 */public void reversed() {int i, j;for (i = array.length - 1, j = 0; i > j; i--, j++) {swap(i, j);}}public void printArray() {for (int i = 0; i < array.length; i++)System.out.print(array[i] + "\t");}}


原创粉丝点击