直接插入排序
基本思想:每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的字序列的合适位置(从后向前找到合适位置后),直到全部插入排序完为止。
public void InsertSort(array a){
int i,j;
for(i = 1; i < a.length; i++){
int temp = a[i];
for(j = i - 1; j >= 0 ; j--){
if(a.[j] > temp){
a.[j+1] = a.[j];
}else{
break;
}
}
a.[j+1] = temp;
}
}
选择排序
基本思想:在要排序的一组数中,选出最小的一个数与第一个位置的数交换;然后在剩下的数当中再找最小的与第二个位置的数交换,如此循环到倒数第二个数和最后一个数比较为止。
public void SelectionSort(array a){
for(int i = 0; i < a.length - 1; i++){
int MinIndex = i;
for(int j = i + 1; j < a.length; j++){
if(a[MinIndex] > a[j]){
MinIndex = j;
}
}
if(MinIndex != i){
int temp = a[i];
a[i] = a[MinIndex];
a[MinIndex] = temp;
}
}
冒泡排序
基本思想:从头开始扫描待排序的元素,在扫描过程中依次对相邻元素进行比较,将关键字值大的元素后移。每经过一趟排序后,关键字值最大的元素将移到末尾,此时记下该元素的位置,下一趟排序只需要比较到此位置为止,直到所有元素都已有序排列。
一般地,对n个元素进行冒泡排序,总共需要进行n-1趟。第1趟需要比较n-1次,第2趟需要比较n-2次,……第i趟需要比较n-i次。
public void BubbleSort(array ar){
for(int i = 0 ; i < ar.length-1; i++) {
for(int j = 0; j < ar.length-1-i; j++){
if(ar[j] >= ar[j+1]){
int temp;
temp = ar[j];
ar[j] = ar[j+1];
ar[j+1] = temp;
}
}
}
}
快速排序(基础版)
//快速排序
void quickSort(int s[], int l, int r) {
if (l < r) {
//Swap(s[l], s[(l + r) / 2]); //将中间的这个数和第一个数交换 参见注1
int i = l, j = r, x = s[l];
while (i < j) {
// 从右向左找第一个小于x的数
while (i < j && s[j] >= x) j--;
if (i < j) s[i++] = s[j];
// 从左向右找第一个大于等于x的数
while (i < j && s[i] < x) i++;
if (i < j) s[j--] = s[i];
}
s[i] = x;
quickSort(s, l, i - 1); // 递归调用
quickSort(s, i + 1, r);
}
}
@Test
public void test() {
int[] a = {6, 2, 4, 5, 7, 1, 9};
quickSort(a, 0, a.length - 1);
System.out.println(a.toString());
}