冒泡排序(Bubble Sort)
依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们交换过来。走访元素的工作是重复地进行直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
public class Test01{
/**
* <h2>冒泡排序</h2>
* <p>
* 使用双重循环,外层循环执行一次内循环执行n次,因为每遍历一次只可以对两个数字进行排序
* 交换规则:如果当前数字比后面一个数字大,那么就交换它们两个的位置
* </p>
* @param arrays
* @return
*/
public static void bubbleSorting(int [] arrays){
int temp=0;
System.err.println(Arrays.toString(arrays));
for(int i=0;i<arrays.length-1;i++) {
for (int j = 0; j < arrays.length - 1; j++) {
if (arrays[j] > arrays[j + 1]) {
temp = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = temp;
}
}
System.out.println(Arrays.toString(arrays));
}
}
public static void main(String[] args) throws Exception {
int [] arrays = new int[]{1000,999,0,3,9,5,300,10,8,20,1,2,100,200,500};
bubbleSorting(arrays);
Thread.sleep(1000);
System.err.println(Arrays.toString(arrays));
}
}
仔细观察控制台输出:
简单选择排序(Simple Select Sort)
简单选择排序也叫最不稳定的排序,待排序记录初始状态是按第一条记录最大,之后的记录从大到小顺序排列,则需要移动记录的次数最多为3(n-1)。简单选择排序过程中需要进行的比较次数与初始状态下待排序的记录序列的排列情况无关。当i=1时,需进行n-1次比较;当i=2时,需进行n-2次比较;依次类推,共需要进行的比较次数是(n-1)+(n-2)+…+2+1=n(n-1)/2,即进行比较操作的时间复杂度为O(n^2),进行移动操作的时间复杂度为O(n)。
public class Test02{
/**
* <h2>选择排序</h2>
* <p>
* 在待排序的数组中找出最小值,然后放在已排序的末尾
* 利用双重循环,找出最小值,再发生一次交换
* </p>
* @param arrays
*/
public static void selectSort(int [] arrays) {
System.err.println(Arrays.toString(arrays));
for (int i = 0; i < arrays.length; i++) {
int temp = 0;
int index = i;
for (int j = i + 1; j < arrays.length; j++) {
//如果后面的值比索引值还小,则将索引值指向数组最后一个比当前值小的索引
if (arrays[j] < arrays[index]) {
index = j;
}
}
//将下标为[i]的值和下标为[index]的值进行交换
temp = arrays[i];
arrays[i] = arrays[index];
arrays[index] = temp;
System.out.println(Arrays.toString(arrays));
}
}
public static void main(String[] args) throws Exception{
int [] arrays = new int[]{5,2,1,0,10,9,100,85,74,25};
selectSort(arrays);
Thread.sleep(1000L);
System.err.println(Arrays.toString(arrays));
}
}
请仔细观察控制台输出:
直接插入排序(Straight Insertion Sort)
直接插入排序(Straight Insertion Sort)是一种最简单的排序方法,其基本操作是将一条记录插入到已排好的有序表中,从而得到一个新的、记录数量增1的有序表,也叫最稳定的排序。
public class Test01 {
public static void insertSort(int [] arrays) throws Exception {
System.err.println(Arrays.toString(arrays));
int value = 0;
for (int i = 0; i < arrays.length - 1; i++) {
value = arrays[i + 1];
for (int j = i + 1; j > 0 && value < arrays[j - 1]; j--) {
arrays[j] = arrays[j - 1];
arrays[j - 1] = value;
}
System.out.println(Arrays.toString(arrays));
}
Thread.sleep(1000L);
System.err.println(Arrays.toString(arrays));
}
public static void main(String[] args) {
try{
int [] arrays = new int[]{4,3,2,1,6,9,10,0,7,8};
insertSort(arrays);
}catch (Exception e){
e.printStackTrace();
}
}
}
请仔细观察控制台输出: