冒泡排序进行了flag标识,略微提高了排序效率;
快速排序使用递归实现。
两种排序算法实现均可以传入规定排序范围的参数以实现局部有序。
import java.util.Random;
public class ComparisonSortingAlgorithm {
public static void main(String[] args) {
Integer[] array = new Integer[10];
Random random = new Random();
for (int i = 0; i < 10; i++) {
array[i] = random.nextInt(100);
System.out.print(array[i] + "\t");
}
System.out.println();
// bubbleSort(array,0,array.length-1);
quickSort(array, 0, array.length - 1);
for (int i = 0; i < 10; i++) {
System.out.print(array[i] + "\t");
}
}
public static <T extends Comparable> void bubbleSort(T[] array, int low, int high) {
if (low < 0 || high > array.length - 1) {
throw new RuntimeException("The sort range is not set properly.");
}
for (int i = high - low; i > 0; i--) {
boolean isExchange = false; //排序过程中是否发生交换,若一轮排序过后未发生交换,直接结束排序过程
for (int j = 0; j < i; j++) {
if (isLes(array, j + 1, j)) {
exc(array, j, j + 1);
isExchange = true;
}
}
if (!isExchange) return;
}
}
public static <T extends Comparable> boolean isLes(T[] array, int i, int j) {//比较数组中两个元素的大小
return array[i].compareTo(array[j]) < 0;
}
public static <T> void exc(T[] array, int i, int j) {//对数组中的元素进行交换
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static <T extends Comparable> int partition(T[] array, int low, int high) {
T pivot = array[low];
while (low < high) {
while (low < high && array[high].compareTo(pivot) >= 0)
high--;
array[low] = array[high];
while (low < high && array[low].compareTo(pivot) <= 0)
low++;
array[high] = array[low];
}
array[low] = pivot;
return low;
}
public static <T extends Comparable> void quickSort(T[] array, int low, int high) {
if (low<0||high>array.length-1){
throw new RuntimeException("The sort range is not set properly.");
}
if (low < high) {
int pivotIndex = partition(array, low, high);
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
}