冒泡排序
冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
//冒泡排序
public static void bubble_sort(int[] aar) {
int temp;
for (int i = 0; i < aar.length; i++) {
for (int j = 0; j < aar.length -i -1; j++) {
if (aar[j] > aar[j + 1]) {
temp = aar[j +1];
aar[j+1] = aar[j];
aar[j] = temp;
}
}
}
}
选择排序
选择排序(Selection-sort)是一种简单直观的排序算法。它的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
//选择排序
public static void select_sort(int arr[]) {
int temp, index;
for (int i = 0; i < arr.length - 1; i++) {
temp = arr[i];
index = i;
for(int j = i +1 ; j < arr.length; j++) {
if (temp > arr[j]) {
index = j;
temp = arr[j];
}
}
if (index != i) {
arr[index] = arr[i];
arr[i] = temp;
}
}
}
插入排序
插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
//插入排序
public static void insert_sort(int arr[]) {
int good_index = 0;
int temp ;
for (int i = 1; i < arr.length; i++) {
int current = arr[i];
for (int j = good_index; j >= 0; j--) {
if (current < arr[j]) {
temp = arr[j];
arr [j] = arr[j + 1];
arr [j + 1] = temp;
current = arr[j];
}
}
good_index++;
}
}