Java算法与数据结构系列(一)排序 sort
github上发现一个算法与数据结构学习的仓库,而且是用java实现的,开个专栏来学习一下。。。
代码会同步到github.
----------------------------分割线------------------------------
为了代码的规范性,我们先来写一个排序的接口吧
package sort;
/**
* sort interface // 排序 java
* author:lzrrr
*/
public interface Sort {
/**
* Main method arrays sorting algorithms
*
* @param unsorted - an array should be sorted
* @param increase - increase or decrease
* @return a sorted array
*/
<T extends Comparable<T>> T[] sort(T[] unsorted, boolean increase);
}
用继承了Comparable接口的泛型来保证数据类型可以进行比较,同时可以选择升序或者降序。
同时,我们在排序过程中可能要用到一些方法(比如两个数的交换、比较、结果输出等),我们也写一个工具类来实现:
package sort;
import java.util.Arrays;
import java.util.List;
/**
这个类用于为排序操作提供一些方法
**/
final class SortUtils{
/**
* Helper method for swapping places in array
*
* @param array The array which elements we want to swap
* @param idx index of the first element
* @param idy index of the second element
*/
static <T> boolean swap(T[] array, int idx, int idy) {
T swap = array[idx];
array[idx] = array[idy];
array[idy] = swap;
return true;
}
/**
* This method checks if first element is less than the other element
*
* @param v first element
* @param w second element
* @return true if the first element is less than the second element
*/
static <T extends Comparable<T>> boolean less(T v, T w) {
return v.compareTo(w) < 0;
}
/**
* This method checks if first element is greater than the other element
*
* @param v first element
* @param w second element
* @return true if the first element is greater than the second element
*/
static <T extends Comparable<T>> boolean greater(T v, T w) {
return v.compareTo(w) > 0;
}
/**
* Prints a list
*
* @param toPrint - a list which should be printed
*/
static void print(List<?> toPrint) {
toPrint.stream()
.map(Object::toString)
.map(str -> str + " ")
.forEach(System.out::print);
System.out.println();
}
/**
* Prints an array
*
* @param toPrint - an array which should be printed
*/
static void print(Object[] toPrint) {
System.out.println(Arrays.toString(toPrint));
}
/**
* Swaps all position from {@param left} to @{@param right} for {@param array}
*
* @param array is an array
* @param left is a left flip border of the array
* @param right is a right flip border of the array
*/
static <T extends Comparable<T>> void flip(T[] array, int left, int right) {
while (left <= right) {
swap(array, left++, right--);
}
}
}
好啦,一切就绪,现在可以开始我们的算法了
选择排序
package sort;
/**
* selection sort // 选择排序 java
* author:lzrrr
* time complexity: O(n^2)
* space complexity: O(1)
* 特点:每一次迭代不改变其他元素的顺序
*/
public class SelectionSort implements Sort{
/**
override the sort method
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] arr, boolean increase) {
for(int i=arr.length-1 ;i>0 ;i--){
int min_index = 0;
for(int j=0 ;j<=i ;j++){
if(increase) {
if (arr[j].compareTo(arr[min_index]) > 0) min_index = j;
}else{
if (arr[j].compareTo(arr[min_index]) < 0) min_index = j;
}
}
//System.out.println(arr[min_index]);
if(min_index!=i)
SortUtils.swap(arr, min_index, i); // use the sortutils swap method
}
return arr;
}
// test
public static void main(String[] args) {
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
SelectionSort selectionSort = new SelectionSort();
// increase
Integer[] sorted = selectionSort.sort(arr, true);
// Output => 1 4 6 9 12 23 54 78 231
SortUtils.print(sorted);
// String Input ; decrease
String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = selectionSort.sort(strings, false);
//Output => a b c d e
SortUtils.print(sortedStrings); // use sortutils method
}
}
冒泡排序
package sort;
/**
* bubble sort // 冒泡排序 java
* author:lzrrr
* time complexity: O(n^2)
* space complexity: O(1)
* 特点:当一次遍历没有做交换时,则说明已经有序,可以退出程序。
*/
public class BubbleSort implements Sort{
@Override // override sort method
public <T extends Comparable<T>> T[] sort(T[] arr, boolean increase){
for(int i=arr.length-1;i>1;i--) {
boolean swaped= false;
for (int j = 0; j < i; j++) {
if (increase) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
SortUtils.swap(arr, j, j + 1); // increase
swaped = true;
}
} else {
if (arr[j].compareTo(arr[j + 1]) < 0) {
SortUtils.swap(arr, j, j + 1); // decrease
swaped = true;
}
}
}
if (!swaped) break; // 没有交换则退出
}
return arr;
}
public static void main(String args[]){
Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12};
BubbleSort BubbleSort = new BubbleSort();
// increase
Integer[] sorted = BubbleSort.sort(arr, true);
// Output => 1 4 6 9 12 23 54 78 231
SortUtils.print(sorted);
// String Input ; decrease
String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = BubbleSort.sort(strings, false);
//Output => a b c d e
SortUtils.print(sortedStrings); // use sortutils method
}
}
快速排序
package sort;
/**
* Quick Sort // 快速排序 java
* author:lzrrr
* time complexity: O(n*log(n))
* space complexity: O(log(n)) // use stack space
* 特点:不稳定,最坏情况时间复杂度为 O(n^2),且需要递归,用到栈空间
*/
public class QuickSort implements Sort{
@Override
public <T extends Comparable<T>> T[] sort(T[] arr,boolean increase){
quicksort(arr,0,arr.length-1);
if (!increase){
for(int i=0;i<arr.length/2;i++)
SortUtils.swap(arr,i,arr.length-1-i);
}
return arr;
}
public <T extends Comparable<T>> void quicksort(T[] arr,int i ,int j){
if (i < j) {
T x = arr[i];
int i1=i,j1=j;
while(i<j) {
while (i < j && arr[j].compareTo(x) >= 0) j--;
if (i < j)
arr[i++] = arr[j];
while (i < j && arr[i].compareTo(x) <= 0) i++;
if (i < j)
arr[j--] = arr[i];
}
arr[i] = x;
quicksort(arr,i1,i-1);
quicksort(arr,i+1,j1);
}
}
public static void main(String args[]){
Integer[] arr = {4,23, 2, 78, 1, 54, 231, 9, 12};
QuickSort QuickSort = new QuickSort();
// increase
SortUtils.print(arr);
Integer[] sorted = QuickSort.sort(arr, true);
// Output => 1 4 6 9 12 23 54 78 231
SortUtils.print(sorted);
// String Input ; decrease
String[] strings = {"c", "a", "e", "b", "d"};
String[] sortedStrings = QuickSort.sort(strings, false);
//Output => a b c d e
SortUtils.print(sortedStrings); // use sortutils method
}
}
待更新。。。
reference
https://github.com/TheAlgorithms/Java