1. 程式人生 > 實用技巧 >初級排序Java版程式碼記錄

初級排序Java版程式碼記錄

package test.sort;

import static io.snowfly.algorithms.sort.SortTest.exchange;
import static io.snowfly.algorithms.sort.SortTest.printArray;

public class SortTest {

    public static void main(String[] args) {
        System.out.println("hello algorithms in java sort");
        int[] arr = {3, 2, 1, 5, 4, 6, 8, 9, 7, 10, 13, 12, 11};
        printArray(arr);
        
//insertSort(arr); //selectSort(arr); //bubbleSort(arr); // mergeSortRecursive(arr, new int[arr.length], 0, arr.length - 1); quickSortRecursive(arr, 0, arr.length - 1); printArray(arr); } static void insertSort(int[] arr) { for (int i = 1; i < arr.length; i++) {
for (int j = i; j > 0 && arr[j] < arr[j - 1]; j--) { exchange(arr, j, j - 1); } } } static void selectSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int index = i; for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[index]) index = j; } if (index != i) exchange(arr, index, i); } } static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) exchange(arr, j, j + 1); } } } static void mergeSortRecursive(int[] arr, int[] rest, int low, int high) { if (low >= high) return; int mid = low + (high - low) / 2; mergeSortRecursive(arr, rest, low, mid); mergeSortRecursive(arr, rest, mid + 1, high); int start1 = low; int end1 = mid; int start2 = mid + 1; int end2 = high; int k = low; while (start1 <= end1 && start2 <= end2) rest[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++]; while (start1 <= end1) rest[k++] = arr[start1++]; while (start2 <= end2) rest[k++] = arr[start2++]; for (k = low; k <= high; k++) { arr[k] = rest[k]; } } static void quickSortRecursive(int[] arr, int low, int high) { if (low >= high) return; int pivot = low; int i = low; int j = high + 1; while (true) { while (arr[++i] < arr[pivot] && i < high) ; while (arr[--j] > arr[pivot] && j > low) ; if (i >= j) break; exchange(arr, i, j); } exchange(arr, pivot, j); quickSortRecursive(arr, low, pivot); quickSortRecursive(arr, pivot + 1, high); } }