/**
* 冒泡排序
* 重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没
* 有再需要交换,也就是说该数列已经排序完成
*
* @param arr
*/
public static int[] bubbleSort(int[] arr) {
int temp;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
/**
* 选择排序
* 在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,
* 然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
*
* @param arr
* @return
*/
public static int[] selectSort(int[] arr) {
int temp;
int minIndex;
for (int i = 0; i < arr.length - 1; i++) {
minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[minIndex] > arr[j]) {
minIndex = j;
}
}
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
return arr;
}
/**
* 插入排序
* 构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入
*
* @param arr
* @return
*/
public static int[] insertSort(int[] arr) {
// 定义前一个索引和当前值
int preIndex, current;
for (int i = 1; i < arr.length; i++) {
preIndex = i - 1;
current = arr[i];
while (preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex + 1] = arr[preIndex];
preIndex--;
}
arr[preIndex + 1] = current;
}
return arr;
}
/**
* 快速排序
*
* @param a 数组
* @param left
* @param right
*/
public static void quickSort(int a[], int left, int right) {
int i, j, t, temp;
if (left > right)
return;
temp = a[left]; //temp中存的就是基准数
i = left;
j = right;
while (i != j) { //顺序很重要,要先从右边开始找
while (a[j] >= temp && i < j)
j--;
while (a[i] <= temp && i < j)//再找左边的
i++;
if (i < j)//交换两个数在数组中的位置
{
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
//最终将基准数归位
a[left] = a[i];
a[i] = temp;
quickSort(a, left, i - 1);//继续处理左边的,这里是一个递归的过程
quickSort(a, i + 1, right);//继续处理右边的 ,这里是一个递归的过程
}