java: Sorting Algorithms
/**
* encoding: utf-8
* 版权所有 2024 ©涂聚文有限公司
* 许可信息查看:
* 描述:
* # Author : geovindu,Geovin Du 涂聚文.
* # IDE : IntelliJ IDEA 2023.1 Java 17
* # Datetime : 2024 - 2024/5/20 - 14:43
* # User : geovindu
* # Product : IntelliJ IDEA
* # Project : EssentialAlgorithms
* # File : Person.java
* # explain : 学习 类
**/
package Model;
/**
* 实体类
* 人
*/
public class Person {
private int id;
private float salary;
private Object someBigObject = new Object();
/**
*
* @param id
* @param salary
*/
public Person(int id, float salary)
{
this.id = id;
this.salary = salary;
}
/**
*
* @return
*/
public float getSalary()
{
return salary;
}
@Override
public String toString()
{
return "Person{" +
"id=" + id +
", salary=" + salary +
", someBigObject=" + someBigObject +
'}';
}
}
/**
* encoding: utf-8
* 版权所有 2024 ©涂聚文有限公司
* 许可信息查看:
* 描述:
* # Author : geovindu,Geovin Du 涂聚文.
* # IDE : IntelliJ IDEA 2023.1 Java 17
* # Datetime : 2024 - 2024/5/20 - 14:49
* # User : geovindu
* # Product : IntelliJ IDEA
* # Project : EssentialAlgorithms
* # File : Node.java
* # explain : 学习 类
**/
package Model;
/**
* 实体类
* 节点
*
*/
public class Node {
public int key;
public Node left, right;
/**
*
* @param item
*/
public Node(int item)
{
key = item;
left = right = null;
}
}
/**
* encoding: utf-8
* 版权所有 2023 ©涂聚文有限公司
* 许可信息查看: https://www.geeksforgeeks.org/sorting-algorithms/
*
* 描述: https://www.programiz.com/dsa/insertion-sort
* # Author : geovindu,Geovin Du 涂聚文. *
* # IDE : IntelliJ IDEA 2023.1 Java 21
* # Datetime : 2023 - 2023/9/28 - 9:55
* # User : geovindu
* # Product : IntelliJ IDEA
* # Project : EssentialAlgorithms
* # File : SortingAlgorithm.java
* # explain : 学习 Sorting Algorithms 类
**/
package SortingAlgorithms;
import java.lang.*;
import java.util.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import Model.Person;
import Model.Node;
public class SortingAlgorithm {
/**
* 1。Bubble Sort冒泡排序法
* @param array 整数数组
*
* */
public static void BubbleSort(int array[]) {
int size = array.length;
// loop to access each array element
for (int i = 0; i < size - 1; i++)
// loop to compare array elements
for (int j = 0; j < size - i - 1; j++)
// compare two adjacent elements
// change > to < to sort in descending order
if (array[j] > array[j + 1]) {
// swapping occurs if elements
// are not in the intended order
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
/**
* 2 Selection Sort 选择排序
* @param array 整数数组
*/
public static void SelectionSort(int array[]) {
int size = array.length;
for (int step = 0; step < size - 1; step++) {
int min_idx = step;
for (int i = step + 1; i < size; i++) {
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
if (array[i] < array[min_idx]) {
min_idx = i;
}
}
// put min at the correct position
int temp = array[step];
array[step] = array[min_idx];
array[min_idx] = temp;
}
}
/**
* 3.Insertion Sort 插入排序
* @param array 整数数组
* */
public static void InsertionSort(int array[]) {
int size = array.length;
for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (j >= 0 && key < array[j]) {
array[j + 1] = array[j];
--j;
}
// Place key at after the element just smaller than it.
array[j + 1] = key;
}
}
/**
*
* @param arr
* @param p
* @param q
* @param r
*/
private static void merge(int arr[], int p, int q, int r) {
// Create L ← A[p..q] and M ← A[q+1..r]
int n1 = q - p + 1;
int n2 = r - q;
int L[] = new int[n1];
int M[] = new int[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
// Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = p;
// Until we reach either end of either L or M, pick larger among
// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
// When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}
}
/**
* Divide the array into two subarrays, sort them and merge them
* 4 Merge Sort 合并/归并排序
* @param arr
* @param l
* @param r
*/
public static void mergeSort(int arr[], int l, int r) {
if (l < r) {
// m is the point where the array is divided into two subarrays
int m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Merge the sorted subarrays
merge(arr, l, m, r);
}
}
/**
* method to find the partition position
* @param array
* @param low
* @param high
* @return
*/
static int partition(int array[], int low, int high) {
// choose the rightmost element as pivot
int pivot = array[high];
// pointer for greater element
int i = (low - 1);
// traverse through all elements
// compare each element with pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
// if element smaller than pivot is found
// swap it with the greatr element pointed by i
i++;
// swapping element at i with element at j
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// swapt the pivot element with the greater element specified by i
int temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
// return the position from where partition is done
return (i + 1);
}
/**
* 5 Quick Sort 快速排序
* @param array 数组
* @param low 开始
* @param high 始束(长度)
*/
public static void quickSort(int array[], int low, int high) {
if (low < high) {
// find pivot element such that
// elements smaller than pivot are on the left
// elements greater than pivot are on the right
int pi = partition(array, low, high);
// recursive call on the left of pivot
quickSort(array, low, pi - 1);
// recursive call on the right of pivot
quickSort(array, pi + 1, high);
}
}
/**
* 6 Counting Sort 计数排序
* @param array 数组
* @param size 长度
*/
public static void countSort(int array[], int size) {
int[] output = new int[size + 1];
// Find the largest element of the array
int max = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > max)
max = array[i];
}
int[] count = new int[max + 1];
// Initialize count array with all zeros.
for (int i = 0; i < max; ++i) {
count[i] = 0;
}
// Store the count of each element
for (int i = 0; i < size; i++) {
count[array[i]]++;
}
// Store the cummulative count of each array
for (int i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
// Find the index of each element of the original array in count array, and
// place the elements in output array
for (int i = size - 1; i >= 0; i--) {
output[count[array[i]] - 1] = array[i];
count[array[i]]--;
}
// Copy the sorted elements into original array
for (int i = 0; i < size; i++) {
array[i] = output[i];
}
}
/**
*
* @param array
* @param size
* @param place
*/
static void countingSort(int array[], int size, int place) {
int[] output = new int[size + 1];
int max = array[0];
for (int i = 1; i < size; i++) {
if (array[i] > max)
max = array[i];
}
int[] count = new int[max + 1];
for (int i = 0; i < max; ++i)
count[i] = 0;
// Calculate count of elements
for (int i = 0; i < size; i++)
count[(array[i] / place) % 10]++;
// Calculate cumulative count
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
// Place the elements in sorted order
for (int i = size - 1; i >= 0; i--) {
output[count[(array[i] / place) % 10] - 1] = array[i];
count[(array[i] / place) % 10]--;
}
for (int i = 0; i < size; i++)
array[i] = output[i];
}
/**
* Function to get the largest element from an array
* @param array
* @param n
* @return
*/
static int getMax(int array[], int n) {
int max = array[0];
for (int i = 1; i < n; i++)
if (array[i] > max)
max = array[i];
return max;
}
/**
* Main function to implement radix sort
* 7 Radix Sort 基数排序
* @param array
* @param size
*/
public static void radixSort(int array[], int size) {
// Get maximum element
int max = getMax(array, size);
// Apply counting sort to sort elements based on place value.
for (int place = 1; max / place > 0; place *= 10)
countingSort(array, size, place);
}
/**
* 8 Bucket Sort 桶排序
* @param arr
* @param n
*/
public void bucketSort(float[] arr, int n) {
if (n <= 0)
return;
@SuppressWarnings("unchecked")
ArrayList<Float>[] bucket = new ArrayList[n];
// Create empty buckets
for (int i = 0; i < n; i++)
bucket[i] = new ArrayList<Float>();
// Add elements into the buckets
for (int i = 0; i < n; i++) {
int bucketIndex = (int) arr[i] * n;
bucket[bucketIndex].add(arr[i]);
}
// Sort the elements of each bucket
for (int i = 0; i < n; i++) {
Collections.sort((bucket[i]));
}
// Get the sorted array
int index = 0;
for (int i = 0; i < n; i++) {
for (int j = 0, size = bucket[i].size(); j < size; j++) {
arr[index++] = bucket[i].get(j);
}
}
}
/**
* 9 Heap Sort 堆排序
* @param arr
*/
public static void heapifySort(int arr[]) {
int n = arr.length;
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Heap sort
for (int i = n - 1; i >= 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Heapify root element
heapify(arr, i, 0);
}
}
/**
*
* @param arr
* @param n
* @param i
*/
static void heapify(int arr[], int n, int i) {
// Find largest among root, left child and right child
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
// Swap and continue heapifying if root is not largest
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
/**
* 10 Shell Sort 希尔排序
* @param array
* @param n
*/
public static void shellSort(int array[], int n) {
for (int interval = n / 2; interval > 0; interval /= 2) {
for (int i = interval; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= interval && array[j - interval] > temp; j -= interval) {
array[j] = array[j - interval];
}
array[j] = temp;
}
}
}
/**
* 11 Linear Search线性搜索
* @param array
* @param x
* @return
*/
public static int linearSearch(int array[], int x) {
int n = array.length;
// Going through array sequencially
for (int i = 0; i < n; i++) {
if (array[i] == x)
return i;
}
return -1;
}
/**
* 12 Binary Search 二分查找
* @param array
* @param x
* @param low
* @param high
* @return
*/
public static int binarySearch(int array[], int x, int low, int high) {
// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
static int bingo;
static int nextBingo;
/**
*
* @param vec
* @param n
*/
private static void maxMin(int[] vec, int n)
{
for (int i = 1; i < n; i++) {
bingo = Math.min(bingo, vec[i]);
nextBingo = Math.max(nextBingo, vec[i]);
}
}
/**
* 13 Bingo Sort宾果排序
* @param vec
* @param n
* @return
*/
public static int[] bingoSort(int[] vec, int n)
{
bingo = vec[0];
nextBingo = vec[0];
maxMin(vec, n);
int largestEle = nextBingo;
int nextElePos = 0;
while (bingo < nextBingo) {
// Will keep the track of the element position
// to
// shifted to their correct position
int startPos = nextElePos;
for (int i = startPos; i < n; i++) {
if (vec[i] == bingo) {
int temp = vec[i];
vec[i] = vec[nextElePos];
vec[nextElePos] = temp;
nextElePos = nextElePos + 1;
}
// Here we are finding the next Bingo
// Element for the next pass
else if (vec[i] < nextBingo)
nextBingo = vec[i];
}
bingo = nextBingo;
nextBingo = largestEle;
}
return vec;
}
static int MIN_MERGE = 32;
/**
*
* @param n
* @return
*/
private static int minRunLength(int n)
{
assert n >= 0;
// Becomes 1 if any 1 bits are shifted off
int r = 0;
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
// This function sorts array from left index to
// to right index which is of size atmost RUN
/**
*
* @param arr
* @param left
* @param right
*/
private static void insertionSort(int[] arr, int left,int right)
{
for (int i = left + 1; i <= right; i++) {
int temp = arr[i];
int j = i - 1;
while (j >= left && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
// Merge function merges the sorted runs
/**
*
* @param arr
* @param l
* @param m
* @param r
*/
public static void timMerge(int[] arr, int l, int m, int r)
{
// Original array is broken in two parts
// left and right array
int len1 = m - l + 1, len2 = r - m;
int[] left = new int[len1];
int[] right = new int[len2];
for (int x = 0; x < len1; x++) {
left[x] = arr[l + x];
}
for (int x = 0; x < len2; x++) {
right[x] = arr[m + 1 + x];
}
int i = 0;
int j = 0;
int k = l;
// After comparing, we merge those two array
// in larger sub array
while (i < len1 && j < len2) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
}
else {
arr[k] = right[j];
j++;
}
k++;
}
// Copy remaining elements
// of left, if any
while (i < len1) {
arr[k] = left[i];
k++;
i++;
}
// Copy remaining element
// of right, if any
while (j < len2) {
arr[k] = right[j];
k++;
j++;
}
}
// Iterative Timsort function to sort the
// array[0...n-1] (similar to merge sort)
/**
* 14 Tim Sort
* @param arr
* @param n
*/
public static void timSort(int[] arr, int n)
{
int minRun = minRunLength(MIN_MERGE);
// Sort individual subarrays of size RUN
for (int i = 0; i < n; i += minRun) {
insertionSort(
arr, i,
Math.min((i + MIN_MERGE - 1), (n - 1)));
}
// Start merging from size
// RUN (or 32). It will
// merge to form size 64,
// then 128, 256 and so on
// ....
for (int size = minRun; size < n; size = 2 * size) {
// Pick starting point
// of left sub array. We
// are going to merge
// arr[left..left+size-1]
// and arr[left+size, left+2*size-1]
// After every merge, we
// increase left by 2*size
for (int left = 0; left < n; left += 2 * size) {
// Find ending point of left sub array
// mid+1 is starting point of right sub
// array
int mid = left + size - 1;
int right = Math.min((left + 2 * size - 1),
(n - 1));
// Merge sub array arr[left.....mid] &
// arr[mid+1....right]
if (mid < right)
timMerge(arr, left, mid, right);
}
}
}
// To find gap between elements
private static int getNextGap(int gap)
{
// Shrink gap by Shrink factor
gap = (gap*10)/13;
if (gap < 1)
return 1;
return gap;
}
// Function to sort arr[] using Comb Sort
/**
*15 Comb Sort
* @param arr
*/
public static void comSort(int arr[])
{
int n = arr.length;
// initialize gap
int gap = n;
// Initialize swapped as true to make sure that
// loop runs
boolean swapped = true;
// Keep running while gap is more than 1 and last
// iteration caused a swap
while (gap != 1 || swapped == true)
{
// Find next gap
gap = getNextGap(gap);
// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;
// Compare all elements with current gap
for (int i=0; i<n-gap; i++)
{
if (arr[i] > arr[i+gap])
{
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i+gap];
arr[i+gap] = temp;
// Set swapped
swapped = true;
}
}
}
}
/**
* 16 Pigeonhole Sort 鸽巢排序
* @param arr
* @param n
*/
public static void pigeonholeSort(int arr[],int n)
{
int min = arr[0];
int max = arr[0];
int range, i, j, index;
for(int a=0; a<n; a++)
{
if(arr[a] > max)
max = arr[a];
if(arr[a] < min)
min = arr[a];
}
range = max - min + 1;
int[] phole = new int[range];
Arrays.fill(phole, 0);
for(i = 0; i<n; i++)
phole[arr[i] - min]++;
index = 0;
for(j = 0; j<range; j++)
while(phole[j]-->0)
arr[index++]=j+min;
}
// Function sort the array using Cycle sort
/**
* 17 Cycle Sort 循环排序
* @param arr
* @param n
*/
public static void cycleSort(int arr[], int n)
{
// count number of memory writes
int writes = 0;
// traverse array elements and put it to on
// the right place
for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) {
// initialize item as starting point
int item = arr[cycle_start];
// Find position where we put the item. We basically
// count all smaller elements on right side of item.
int pos = cycle_start;
for (int i = cycle_start + 1; i < n; i++)
if (arr[i] < item)
pos++;
// If item is already in correct position
if (pos == cycle_start)
continue;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it's right position
if (pos != cycle_start) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
// Rotate rest of the cycle
while (pos != cycle_start) {
pos = cycle_start;
// Find position where we put the element
for (int i = cycle_start + 1; i < n; i++)
if (arr[i] < item)
pos += 1;
// ignore all duplicate elements
while (item == arr[pos])
pos += 1;
// put the item to it's right position
if (item != arr[pos]) {
int temp = item;
item = arr[pos];
arr[pos] = temp;
writes++;
}
}
}
}
/**
* 18 Cocktail Sort 鸡尾酒排序
* @param a
*/
public static void cocktailSort(int a[])
{
boolean swapped = true;
int start = 0;
int end = a.length;
while (swapped == true)
{
// reset the swapped flag on entering the
// loop, because it might be true from a
// previous iteration.
swapped = false;
// loop from bottom to top same as
// the bubble sort
for (int i = start; i < end - 1; ++i)
{
if (a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
// if nothing moved, then array is sorted.
if (swapped == false)
break;
// otherwise, reset the swapped flag so that it
// can be used in the next stage
swapped = false;
// move the end point back by one, because
// item at the end is in its rightful spot
end = end - 1;
// from top to bottom, doing the
// same comparison as in the previous stage
for (int i = end - 1; i >= start; i--)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
swapped = true;
}
}
// increase the starting point, because
// the last stage would have moved the next
// smallest number to its rightful spot.
start = start + 1;
}
}
// Define a helper function to merge two sorted lists
/**
*
* @param list1
* @param list2
* @return
*/
private static List<Integer> mergeLists(List<Integer> list1, List<Integer> list2) {
List<Integer> result = new ArrayList<>();
while (!list1.isEmpty() && !list2.isEmpty()) {
if (list1.get(0) < list2.get(0)) {
result.add(list1.remove(0));
} else {
result.add(list2.remove(0));
}
}
result.addAll(list1);
result.addAll(list2);
return result;
}
// Recursive function to perform strand sort
/**
* 19 Strand Sort 经典排序
* @param inputList
* @return
*/
public static List<Integer> strandSort(List<Integer> inputList) {
// Base case: if the input list has 1 or fewer elements, it's already sorted
if (inputList.size() <= 1) {
return inputList;
}
// Initialize a sublist with the first element of the input list
List<Integer> sublist = new ArrayList<>();
sublist.add(inputList.remove(0));
int i = 0;
while (i < inputList.size()) {
// If the current element in the input list is greater than
// the last element in the sublist,
// add it to the sublist; otherwise, continue to the next element in the input list.
if (inputList.get(i) > sublist.get(sublist.size() - 1)) {
sublist.add(inputList.remove(i));
} else {
i++;
}
}
// The sortedSublist contains the sorted elements from the current sublist
List<Integer> sortedSublist = new ArrayList<>(sublist);
// Recursively sort the remaining part of the input list
List<Integer> remainingList = strandSort(inputList);
// Merge the sorted sublist and the sorted remainingList
return mergeLists(sortedSublist, remainingList);
}
/* The parameter dir indicates the sorting direction,
ASCENDING or DESCENDING; if (a[i] > a[j]) agrees
with the direction, then a[i] and a[j] are
interchanged. */
private static void compAndSwap(int a[], int i, int j, int dir)
{
if ( (a[i] > a[j] && dir == 1) ||
(a[i] < a[j] && dir == 0))
{
// Swapping elements
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
/* It recursively sorts a bitonic sequence in ascending
order, if dir = 1, and in descending order otherwise
(means dir=0). The sequence to be sorted starts at
index position low, the parameter cnt is the number
of elements to be sorted.*/
private static void bitonicMerge(int a[], int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
for (int i=low; i<low+k; i++)
compAndSwap(a,i, i+k, dir);
bitonicMerge(a,low, k, dir);
bitonicMerge(a,low+k, k, dir);
}
}
/* This function first produces a bitonic sequence by
recursively sorting its two halves in opposite sorting
orders, and then calls bitonicMerge to make them in
the same order */
private static void getBitonicSort(int a[], int low, int cnt, int dir)
{
if (cnt>1)
{
int k = cnt/2;
// sort in ascending order since dir here is 1
getBitonicSort(a, low, k, 1);
// sort in descending order since dir here is 0
getBitonicSort(a,low+k, k, 0);
// Will merge whole sequence in ascending order
// since dir=1.
bitonicMerge(a, low, cnt, dir);
}
}
/*Caller of bitonicSort for sorting the entire array
of length N in ASCENDING order */
/**
* 20 Bitonic Sort 双调排序
* @param a
* @param N
* @param up
*/
public static void BitonicSort(int a[], int N, int up)
{
getBitonicSort(a, 0, N, up);
}
/* Reverses arr[0..i] */
/**
*
* @param arr
* @param i
*/
private static void flip(int arr[], int i)
{
int temp, start = 0;
while (start < i)
{
temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
start++;
i--;
}
}
// Returns index of the
// maximum element in
// arr[0..n-1]
/**
*
* @param arr
* @param n
* @return
*/
private static int findMax(int arr[], int n)
{
int mi, i;
for (mi = 0, i = 0; i < n; ++i)
if (arr[i] > arr[mi])
mi = i;
return mi;
}
// The main function that
// sorts given array using
// flip operations
/**
* 21 Pancake Sort 煎饼排序.
* @param arr
* @param n
* @return
*/
public static int pancakeSort(int arr[], int n)
{
// Start from the complete
// array and one by one
// reduce current size by one
for (int curr_size = n; curr_size > 1;
--curr_size)
{
// Find index of the
// maximum element in
// arr[0..curr_size-1]
int mi = findMax(arr, curr_size);
// Move the maximum element
// to end of current array
// if it's not already at
// the end
if (mi != curr_size-1)
{
// To move at the end,
// first move maximum
// number to beginning
flip(arr, mi);
// Now move the maximum
// number to end by
// reversing current array
flip(arr, curr_size-1);
}
}
return 0;
}
// Sorts array a[0..n-1] using Bogo sort
/**
* 22 Bogo Sort BogoSort or Permutation Sort 置换排序、愚蠢排序、慢排序、猎枪排序或猴子排序
* @param a
*/
public static void bogoSort(int[] a)
{
// if array is not sorted then shuffle the
// array again
while (isSorted(a) == false)
shuffle(a);
}
// To generate permutation of the array
/**
*
* @param a
*/
private static void shuffle(int[] a)
{
// Math.random() returns a double positive
// value, greater than or equal to 0.0 and
// less than 1.0.
for (int i = 1; i < a.length; i++)
bogoSwap(a, i, (int)(Math.random() * i));
}
// Swapping 2 elements
/**
*
* @param a
* @param i
* @param j
*/
private static void bogoSwap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// To check if array is sorted or not
/**
*
* @param a
* @return
*/
private static boolean isSorted(int[] a)
{
for (int i = 1; i < a.length; i++)
if (a[i] < a[i - 1])
return false;
return true;
}
/**
* 23 Gnome Sort 地精排序,也称侏儒排序
* @param arr
* @param n
*/
public static void gnomeSort(int arr[], int n)
{
int index = 0;
while (index < n) {
if (index == 0)
index++;
if (arr[index] >= arr[index - 1])
index++;
else {
int temp = 0;
temp = arr[index];
arr[index] = arr[index - 1];
arr[index - 1] = temp;
index--;
}
}
return;
}
/**
* 24.Sleep Sort 睡眠排序
* @param arr
*/
public static void sleepSort(ArrayList<Integer> arr) {
ArrayList<Thread> threads = new ArrayList<>(); // Create an ArrayList to hold threads
for (int num : arr) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(num); // Sleep for 'num' milliseconds
System.out.print(num + " "); // Print the number after sleeping
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threads.add(thread); // Add the thread to the ArrayList
thread.start(); // Start the thread
}
for (Thread thread : threads) {
try {
thread.join(); // Wait for each thread to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Function to implement stooge sort
/**
* 25 Stooge Sort 臭皮匠排序
* @param arr
* @param l
* @param h
*/
public static void stoogeSort(int arr[], int l, int h)
{
if (l >= h)
return;
// If first element is smaller
// than last, swap them
if (arr[l] > arr[h]) {
int t = arr[l];
arr[l] = arr[h];
arr[h] = t;
}
// If there are more than 2 elements in
// the array
if (h - l + 1 > 2) {
int t = (h - l + 1) / 3;
// Recursively sort first 2/3 elements
stoogeSort(arr, l, h - t);
// Recursively sort last 2/3 elements
stoogeSort(arr, l + t, h);
// Recursively sort first 2/3 elements
// again to confirm
stoogeSort(arr, l, h - t);
}
}
// Modifying tag array so that we can access
// persons in sorted order of salary.
/**
* 26 Tag Sort (To get both sorted and original)
* @param persons
* @param tag
*/
public static void tagSort(Person persons[],int tag[])
{
int n = persons.length;
for (int i=0; i<n; i++)
{
for (int j=i+1; j<n; j++)
{
if (persons[tag[i]].getSalary() >
persons[tag[j]].getSalary())
{
// Note we are not sorting the
// actual Persons array, but only
// the tag array
int temp = tag[i];
tag[i] = tag[j];
tag[j] = temp;
}
}
}
}
public static Node root;
// This method mainly
// calls insertRec()
/**
*
* @param key
*/
private static void treeInsert(int key)
{
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
/**
*
* @param root
* @param key
* @return
*/
private static Node insertRec(Node root, int key)
{
/* If the tree is empty,
return a new node */
if (root == null)
{
root = new Node(key);
return root;
}
/* Otherwise, recur
down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the root */
return root;
}
// A function to do
// inorder traversal of BST
/**
*27 Tree Sort
* @param root
*/
public static void inorderRec(Node root)
{
if (root != null)
{
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}
/**
*
* @param arr
*/
public static void treeins(int arr[])
{
for(int i = 0; i < arr.length; i++)
{
treeInsert(arr[i]);
}
}
/**
* 28.Brick Sort / Odd-Even Sort 砖排序算法(Brick Sort),也被称为奇偶排序(Odd-Even Sort)
* @param arr
* @param n
*/
public static void oddEvenSort(int arr[], int n)
{
boolean isSorted = false; // Initially array is unsorted
while (!isSorted)
{
isSorted = true;
int temp =0;
// Perform Bubble sort on odd indexed element
for (int i=1; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
isSorted = false;
}
}
// Perform Bubble sort on even indexed element
for (int i=0; i<=n-2; i=i+2)
{
if (arr[i] > arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
isSorted = false;
}
}
}
return;
}
// Function for 3-way merge sort process
/**
* 29.3-way Merge Sort
* @param gArray
*/
public static void mergeSort3Way(Integer[] gArray)
{
// if array of size is zero returns null
if (gArray == null)
return;
// creating duplicate of given array
Integer[] fArray = new Integer[gArray.length];
// copying elements of given array into
// duplicate array
for (int i = 0; i < fArray.length; i++)
fArray[i] = gArray[i];
// sort function
mergeSort3WayRec(fArray, 0, gArray.length, gArray);
// copy back elements of duplicate array
// to given array
for (int i = 0; i < fArray.length; i++)
gArray[i] = fArray[i];
}
/* Performing the merge sort algorithm on the
given array of values in the rangeof indices
[low, high). low is minimum index, high is
maximum index (exclusive) */
/**
*
* @param gArray
* @param low
* @param high
* @param destArray
*/
public static void mergeSort3WayRec(Integer[] gArray,int low, int high, Integer[] destArray)
{
// If array size is 1 then do nothing
if (high - low < 2)
return;
// Splitting array into 3 parts
int mid1 = low + ((high - low) / 3);
int mid2 = low + 2 * ((high - low) / 3) + 1;
// Sorting 3 arrays recursively
mergeSort3WayRec(destArray, low, mid1, gArray);
mergeSort3WayRec(destArray, mid1, mid2, gArray);
mergeSort3WayRec(destArray, mid2, high, gArray);
// Merging the sorted arrays
WayMerge(destArray, low, mid1, mid2, high, gArray);
}
/* Merge the sorted ranges [low, mid1), [mid1,
mid2) and [mid2, high) mid1 is first midpoint
index in overall range to merge mid2 is second
midpoint index in overall range to merge*/
/**
*
* @param gArray
* @param low
* @param mid1
* @param mid2
* @param high
* @param destArray
*/
public static void WayMerge(Integer[] gArray, int low,int mid1, int mid2, int high,Integer[] destArray)
{
int i = low, j = mid1, k = mid2, l = low;
// choose smaller of the smallest in the three ranges
while ((i < mid1) && (j < mid2) && (k < high))
{
if (gArray[i].compareTo(gArray[j]) < 0)
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[k++];
}
else
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
}
// case where first and second ranges have
// remaining values
while ((i < mid1) && (j < mid2))
{
if (gArray[i].compareTo(gArray[j]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[j++];
}
// case where second and third ranges have
// remaining values
while ((j < mid2) && (k < high))
{
if (gArray[j].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[j++];
else
destArray[l++] = gArray[k++];
}
// case where first and third ranges have
// remaining values
while ((i < mid1) && (k < high))
{
if (gArray[i].compareTo(gArray[k]) < 0)
destArray[l++] = gArray[i++];
else
destArray[l++] = gArray[k++];
}
// copy remaining values from the first range
while (i < mid1)
destArray[l++] = gArray[i++];
// copy remaining values from the second range
while (j < mid2)
destArray[l++] = gArray[j++];
// copy remaining values from the third range
while (k < high)
destArray[l++] = gArray[k++];
}
}
/**
* encoding: utf-8
* 版权所有 2023 ©涂聚文有限公司
* 许可信息查看:
* 描述:
* # Author : geovindu,Geovin Du 涂聚文.
* # IDE : IntelliJ IDEA 2023.1 Java 21
* # Datetime : 2023 - 2023/9/28 - 10:00
* # User : geovindu
* # Product : IntelliJ IDEA
* # Project : EssentialAlgorithms
* # File : SortingExmaple.java
* # explain : 学习 Sorting Algorithms 类
**/
package BLL;
import SortingAlgorithms.SortingAlgorithm;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import Model.Person;
import Model.Node;
public class SortingExmaple {
/**
*1.Bubble Sort冒泡排序
* */
public static void Bubble()
{
int[] geovindu = { -2, 45, 0, 11, -9 };
// call method using class name
SortingAlgorithms.SortingAlgorithm.BubbleSort(geovindu);
System.out.println("1.冒泡排序 Sort Bubble Sorted Array in Ascending Order:");
System.out.println(Arrays.toString(geovindu));
}
/**
* 2 Selection Sort 选择排序
*/
public static void Selection()
{
int[] geovindu = { 20, 12, 10, 15, 2 };
//SelectionSort ss = new SelectionSort();
SortingAlgorithms.SortingAlgorithm.SelectionSort(geovindu);
System.out.println("2.选择排序 Selection Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(geovindu));
}
/**
* 3. Insertion Sort 插入排序
* */
public static void Insertion()
{
int[] geovindu = { 9, 5, 1, 4, 3 };
SortingAlgorithms.SortingAlgorithm.InsertionSort(geovindu);
System.out.println("3.插入排序 Insertion Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(geovindu));
}
/**
* 4 Merge Sort 合并/归并排序
*/
public static void mergeSort()
{
int arr[] = { 6, 5, 12, 10, 9, 1 };
SortingAlgorithms.SortingAlgorithm.mergeSort(arr, 0, arr.length - 1);
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
/**
* 5 Quick Sort 快速排序
*/
public static void quicksort()
{
int[] data = { 8, 7, 2, 1, 0, 9, 6 };
System.out.println("Unsorted Array");
System.out.println(Arrays.toString(data));
int size = data.length;
// call quicksort() on array data
SortingAlgorithms.SortingAlgorithm.quickSort(data, 0, size - 1);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
/**
* 6 Counting Sort 计数排序
*/
public static void countSort()
{
int[] data = { 4, 2, 2, 8, 3, 3, 1 };
int size = data.length;
SortingAlgorithms.SortingAlgorithm.countSort(data, size);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
/**
* 7 Radix Sort 基数排序
*/
public static void radixSort()
{
int[] data = { 121, 432, 564, 23, 1, 45, 788 };
int size = data.length;
SortingAlgorithms.SortingAlgorithm.radixSort(data, size);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
/**
* 9 Heap Sort 堆排序
*/
public static void heapifySort()
{
int arr[] = { 1, 12, 9, 5, 6, 10 };
SortingAlgorithms.SortingAlgorithm.heapifySort(arr);
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
/**
* 10 Shell Sort 希尔排序
*/
public static void shellSort()
{
int[] data = { 9, 8, 3, 7, 5, 6, 4, 1 };
int size = data.length;
SortingAlgorithms.SortingAlgorithm.shellSort(data, size);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
/**
* 12 Binary Search 二分查找
*/
public static void binarySearch()
{
int array[] = { 3, 4, 5, 6, 7, 8, 9 };
int n = array.length;
int x = 4;
int result = SortingAlgorithms.SortingAlgorithm.binarySearch(array, x, 0, n - 1);
if (result == -1)
System.out.println("Not found");
else
System.out.println("Element found at index " + result);
}
/**
* 13 Bingo Sort宾果排序
*/
public static void binggoSor()
{
int[] arr = { 5, 4, 8, 5, 4, 8, 5, 4, 4, 4 };
arr = SortingAlgorithms.SortingAlgorithm.bingoSort(arr, arr.length);
int n=arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
/**
*14 Tim Sort
*/
public static void timSort()
{
int[] arr = { -2, 7, 15, -14, 0, 15, 0, 7,
-7, -4, -13, 5, 8, -14, 12 };
int n = arr.length;
System.out.println("Given Array is");
SortingAlgorithms.SortingAlgorithm.timSort(arr, n);
System.out.println("After Sorting Array is");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.print("\n");
}
/**
* 15 Comb Sort
*/
public static void comSort()
{
int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
SortingAlgorithms.SortingAlgorithm.comSort(arr);
System.out.println("sorted array");
for (int i=0; i<arr.length; ++i)
System.out.print(arr[i] + " ");
}
/**
* 16 Pigeonhole Sort 鸽巢排序
*/
public static void pigeonholeSort()
{
int[] arr = {8, 3, 2, 7, 4, 6, 8};
System.out.print("Sorted order is : ");
SortingAlgorithms.SortingAlgorithm.pigeonholeSort(arr,arr.length);
for(int i=0 ; i<arr.length ; i++)
System.out.print(arr[i] + " ");
}
/**
* 17 Cycle Sort 循环排序
*/
public static void cycleSort()
{
int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 };
int n = arr.length;
SortingAlgorithms.SortingAlgorithm.cycleSort(arr, n);
System.out.println("After sort : ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
/**
* 18 Cocktail Sort 鸡尾酒排序
*/
public static void cocktailSort()
{
int[] arr = {5, 2, 9, 3, 7, 6};
SortingAlgorithms.SortingAlgorithm.cocktailSort(arr);
System.out.println(Arrays.toString(arr));
}
/**
* 19 Strand Sort 经典排序
*/
public static void strandSort()
{
List<Integer> inputList = new ArrayList<>();
inputList.add(10);
inputList.add(5);
inputList.add(30);
inputList.add(40);
inputList.add(2);
inputList.add(4);
inputList.add(9);
List<Integer> outputList = SortingAlgorithms.SortingAlgorithm.strandSort(inputList);
for (int x : outputList) {
System.out.print(x + " ");
}
}
/**
* 20 Bitonic Sort 双调排序
*/
public static void BitonicSort()
{
int arr[] = {3, 7, 4, 8, 6, 2, 1, 5};
int up = 1;
SortingAlgorithms.SortingAlgorithm.BitonicSort(arr, arr.length,up);
System.out.println("\nSorted array");
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
/**
* 21 Pancake Sort 煎饼排序.
*/
public static void pancakeSort()
{
int arr[] = {23, 10, 20, 11, 12, 6, 7};
int n = arr.length;
SortingAlgorithms.SortingAlgorithm.pancakeSort(arr, n);
System.out.println("Sorted Array: ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
/**
* 22 Bogo Sort BogoSort or Permutation Sort 置换排序、愚蠢排序、慢排序、猎枪排序或猴子排序
*/
public static void bogoSort()
{
// Enter array to be sorted here
int[] arr = { 3, 2, 5, 1, 0, 4 };
SortingAlgorithms.SortingAlgorithm.bogoSort(arr);
System.out.print("Sorted array: ");
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
/**
* 23 Gnome Sort 地精排序,也称侏儒排序
*/
public static void gnomeSort()
{
int arr[] = { 34, 2, 10, -9 };
SortingAlgorithms.SortingAlgorithm.gnomeSort(arr, arr.length);
System.out.print("Sorted sequence after applying Gnome sort: ");
System.out.println(Arrays.toString(arr));
}
/**
* 24.Sleep Sort 睡眠排序
*/
public static void sleepSort()
{
ArrayList<Integer> arr = new ArrayList<>();
arr.add(34); // Add elements to the ArrayList
arr.add(23);
arr.add(122);
arr.add(9);
SortingAlgorithms.SortingAlgorithm.sleepSort(arr); // Call the sleepSort function to sort the ArrayList
}
/**
* 25 Stooge Sort 臭皮匠排序
*/
public static void stoogeSort()
{
int arr[] = { 2, 4, 5, 3, 1 };
int n = arr.length;
SortingAlgorithms.SortingAlgorithm.stoogeSort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
/**
* 26 Tag Sort
*/
public static void tagSort()
{
// Creating objects and their original
// order (in tag array)
int n = 5;
Person persons[] = new Person[n];
persons[0] = new Person(0, 233.5f);
persons[1] = new Person(1, 23f);
persons[2] = new Person(2, 13.98f);
persons[3] = new Person(3, 143.2f);
persons[4] = new Person(4, 3f);
int tag[] = new int[n];
for (int i = 0; i < n; i++)
tag[i] = i;
// Every Person object is tagged to
// an element in the tag array.
System.out.println("Given Person and Tag ");
for (int i = 0; i < n; i++)
System.out.println(persons[i] +
" : Tag: " + tag[i]);
// Modifying tag array so that we can access
// persons in sorted order.
SortingAlgorithms.SortingAlgorithm.tagSort(persons, tag);
System.out.println("New Tag Array after "+
"getting sorted as per Person[] ");
for (int i=0; i<n; i++)
System.out.println(tag[i]);
// Accessing persons in sorted (by salary)
// way using modified tag array.
for (int i = 0; i < n; i++)
System.out.println(persons[tag[i]]);
}
/**
* 27 Tree Sort
*/
public static void TreeSort()
{
// Node root;
int arr[] = {5, 4, 7, 2, 11};
SortingAlgorithms.SortingAlgorithm.treeins(arr);
SortingAlgorithms.SortingAlgorithm.inorderRec(SortingAlgorithms.SortingAlgorithm.root);
}
/**
* 28.Brick Sort / Odd-Even Sort 砖排序算法(Brick Sort),也被称为奇偶排序(Odd-Even Sort)
*/
public static void BrickSort()
{
int arr[] = {34, 2, 10, -9};
int n = arr.length;
SortingAlgorithms.SortingAlgorithm.oddEvenSort(arr, n);
for (int i=0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println(" ");
}
/**
* 29.3-way Merge Sort
*/
public static void mergeSort3Way()
{
// test case of values
Integer[] data = new Integer[] {45, -2, -45, 78,
30, -42, 10, 19, 73, 93};
SortingAlgorithms.SortingAlgorithm.mergeSort3Way(data);
System.out.println("After 3 way merge sort: ");
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
}
}
调用:
/**
* encoding: utf-8
* 版权所有 2023 ©涂聚文有限公司
* 许可信息查看:
* 描述:
* # Author : geovindu,Geovin Du 涂聚文. *
* # IDE : IntelliJ IDEA 2023.1 Java 21
*
* # Datetime : 2023 - 2023/9/28 - 9:55
* # User : geovindu
* # Product : IntelliJ IDEA
* # Project : EssentialAlgorithms
* # File : Main.java
* # explain : 学习 Sorting Algorithms 类
**/
import BLL.SortingExmaple;
public class Main {
/**
*
* */
public static void main(String[] args)
{
System.out.println("Hello world! Java, 涂聚文 geovindu Geovin Du 学习Java");
// 1.Bubble Sort冒泡排序法
SortingExmaple.Bubble();
//2.
SortingExmaple.Selection();
//3.
SortingExmaple.Insertion();
}
}
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
浙公网安备 33010602011771号