最近整理自己的学习笔记,又看了关于排序的算法,贴出来方便别人学习和自己复习,下次发一些关于排序算法优化的代码。
package cn.sort;
public class All_Of_Sort {
/**
* 选择排序
*/
public static void selectSort(int[] a){
int temp = 0; //用来交换的临时变量
int minIndex = 0; //最小数的下标
if(a == null && a.length == 0){
return;
}
for(int i = 0; i < a.length; i++){
minIndex = i;
for(int j = i+1; j < a.length; j++){
if(a[j] < a[minIndex]){
minIndex = j;
}
}
//交换位置
if(minIndex != i){
temp = a[i];
a[i] = a[minIndex];
a[minIndex] = temp;
}
}
}
/**
* 快速排序
*/
public static void quickSort(int[] a, int start, int end){
int i = start;
int j = end;
int key = a[start];
while(i < j){
while(j > i && a[j] >= key){
j--;
}
if(i < j){
a[i] = a[j];
}
while(i < j && a[i] < key){
i++;
}
if(i < j){
a[j] = a[i];
}
}
a[i] = key;
if(i - start > 1){
quickSort(a, start, i-1);
}
if(end - j > 1){
quickSort(a, j+1, end);
}
}
/**
* 冒泡排序
* 第一个和后面全部比,找出最小的与第一个交换位置
* 第二个和后面全部比,找出最小的与第二个交换位置
* @param a
*/
public static void bubbleSort(int[] a){
int temp = 0;
for(int i = 0; i < a.length -1; i++){
for(int j = i; j < a.length - 1 - i; j++){
if(a[j+1] < a[j])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
/**
* 插入排序
* @param a
*/
public static void insertSort(int[] a){
for(int i = 1; i < a.length; i++){
int temp = a[i];
// temp准备和前一个数比较
int index = i -1;
while(index >= 0 && temp < a[index]){
// 将把a[index]向后移动
a[index + 1] = a[index];
// 让index向前移动一位
index--;
}
// 将temp插入到适当位置
a[index + 1] = temp;
}
}
public static void main(String[] args) {
int[] num = {20, 30, 98, 50, 4, 6, 76};
selectSort(num);
for(int i : num){
System.out.print(" " + i);
}
System.out.println();
quickSort(num, 0, num.length-1);
for(int i : num){
System.out.print(" " + i);
}
System.out.println();
bubbleSort(num);
for(int i : num){
System.out.print(" " + i);
}
System.out.println();
insertSort(num);
for(int i : num){
System.out.print(" " + i);
}
}
}