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(最?。褂肙UT標記最左邊未排序的數據,然后使用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");
}
}
作者:chengchanglun 發表于2012-4-13 13:50:01
原文鏈接