1.冒泡排序
- 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
- 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
- 针对所有的元素重复以上的步骤,除了最后一个。
- 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
package sort;
public class BubbleSort {
public int[] bubbleSort(int[] b) {
boolean flag = true; // 默认有序
for (int i = 0; i < b.length - 1;i++) {
for (int j = 0; j < b.length - 1 - i; j++ ){
if (b[j] > b[j+1]){
b[j] = b[j] ^ b[j+1];
b[j+1] = b[j] ^ b[j+1];
b[j] = b[j] ^ b[j+1];
flag = false; // 发生交换,则判定不是有序的。
}
}
if (flag) {
// 如果有一轮没有发生交换,说明已经有序,则可以退出算法。
break;
}
}
return b;
}
public static void main(String[] args) {
int[] a = {0,3,2,46,5,56,35,631,31,-1};
new BubbleSort().bubbleSort(a);
for (int x: a) {
System.out.println(x);
}
}
}
2.选择排序
基本思想。实现思想是每步从排序记录中选出排序码最小(最大)的记录,放在已排序记录序列的最后(前)
package sort;
import javax.persistence.criteria.CriteriaBuilder;
public class SelectSort {
public int[] selectSort(int[] b) {
int min,temp;
for (int i = 0; i < b.length;i++) {
min = i;
for (int j = i+1; j < b.length; j++){
if (b[j] < b[min]){ // 找到最小元素的坐标。
min = j;
}
}
// 如果此时最小元素不是默认i位置的元素,则发生交换。
if (min!=i){
temp = b[min];
b[min] = b[i];
b[i] = temp;
}
}
return b;
}
public static void main(String[] args) {
int[] a = {0,0,2,46,5,56,35,631,31,-1};
new SelectSort().selectSort(a);
for (int x: a) {
System.out.println(x);
}
}
}
3.快速排序
-
从数列中挑出一个元素,称为 “基准”(pivot);
-
重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
-
递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序;
package sort;
import javax.persistence.criteria.CriteriaBuilder;
public class SelectSort {
public int[] quickSort(int[] arr, int left, int right) {
if (left < right) {
int partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}
private int partition(int[] arr, int left, int right) {
// 设定基准值(pivot)
int pivot = left;
int index = pivot + 1;
for (int i = index; i <= right; i++) {
if (arr[i] < arr[pivot]) {
swap(arr, i, index);
index++;
}
}
swap(arr, pivot, index - 1);
return index - 1;
}
private void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] a = {0,3,2,46,5,56,35,631,31,-1};
new SelectSort().quickSort(a,0,a.length -1);
for (int x: a) {
System.out.println(x);
}
}
}