python javascript java golang scala shell
俩 j 语言 加分号是比较好的写法
golang编码规范
scala编码规范
python Utils.py
class Utils(object):
def __init__(self, arr):
self.arr = arr
self.arr_len = len(self.arr)
def bubbleSort(self):
for i in range(0, self.arr_len, 1):
for j in range(0, self.arr_len - 1 - i, 1):
if self.arr[j] > self.arr[j+1]:
self.swap(self.arr, j, j+1)
def swap(self, arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def selectSort(self):
for i in range(0, self.arr_len, 1):
for j in range(i+1, self.arr_len, 1):
if self.arr[i] > self.arr[j]:
self.swap(self.arr, i, j)
def insertSort(self):
for i in range(0, self.arr_len, 1):
for j in range(i, 0, -1):
if self.arr[j] < self.arr[j-1]:
self.swap(self.arr, j-1, j)
def partition(self,low, high):
pivot = arr[low]
while(low < high):
while(low < high and self.arr[high] > pivot):
high -= 1
self.arr[low] = self.arr[high]
while(low < high and self.arr[low] < pivot):
low += 1
self.arr[high] = self.arr[low]
self.arr[low] = pivot
return low
def quickSort(self, low, high):
# low = 0 if not low else low
# high = self.arr_len if not high else high
if(low < high):
pivot = self.partition(low, high)
self.quickSort(low, pivot - 1)
self.quickSort(pivot + 1, high)
if __name__ == '__main__':
arr = [10,9,8,7,6,5,4,3,2,1]
print(arr)
# Utils(arr).bubbleSort()
# Utils(arr).selectSort()
# Utils(arr).insertSort()
Utils(arr).quickSort(0, len(arr) - 1)
print(arr)`
javascript Utils.js
// 亦或 交换数组的值
function swap(arr, i, j){
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
// 冒泡排序
function bubbleSort(arr){
for(let i=0; i<arr.length; i++){
for(let j=0; j<arr.length - i -1; j++){
if(arr[j] > arr[j+1]){
swap(arr, j, j+1);
}
}
}
//return arr;
}
// 选择排序
function selectSort(arr){
for(i=0; i<arr.length; i++){
for(j=i+1;j<arr.length;j++){
if(arr[i] > arr[j]){
swap(arr, i, j);
}
}
}
}
// 插入排序
function insertSort(arr){
for(i=0; i<arr.length; i++){
for(j=i; j>0; j--){
if(arr[j] < arr[j-1]){
swap(arr, j, j-1);
}
}
}
}
// 快速排序
function partition(arr, low , high){
let pivot = arr[low];
while(low < high){
while(low < high && arr[high] > pivot){
--high;
}
arr[low] = arr[high];
while(low<high && arr[low] < pivot){
++low;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
function quickSort(arr, low, high){
if(low === undefined && high === undefined){
low = 0;
high = arr.length-1;
}
if(low < high){
let pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
return arr;
}
var arr = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
console.log(arr);
//bubbleSort(arr)
//selectSort(arr)
//insertSort(arr);
quickSort(arr);
console.log(arr);
***java Utils.java ***
class SortUtils{
private static <T extends Comparable<? super T>> int partition(T[] arr, int low, int high){
// 找到基准值
T pivot = arr[low]; // 把 low 这个坑挖出来了
// low, high 两根 "指针"
while(low < high){
// 从右边开始向左查找是否有比基准值小的值
while(low < high && arr[high].compareTo(pivot) == 1){
--high;
}
// 跳出上面的循环,意味着从右->左, 找到找到了比基准值小的值
arr[low] = arr[high];
// 然后从左往右找是否有比基准值大的值
while(low < high && arr[low].compareTo(pivot) == -1 ){
++low;
}
// 跳出上面的循环,意味着从左->右, 找到了比基准值大的值, 填坑
arr[high] = arr[low];
}
// 最后把 pivot 基准值回填到 low 里
arr[low] = pivot;
// 将此刻基准值的下标 返出去,用于下次快排分区的左右 index +- 1 临界下标
return low;
}
public static <T extends Comparable<? super T>> void quickSort(T[] arr){
quickSort(arr, 0, arr.length-1);
}
private static <T extends Comparable<? super T>> void quickSort(T[] arr, int low, int high){
if(low < high){
// 分区
int pivot = partition(arr, low, high);
// 对分区分别递归快排
// 左分区排序
quickSort(arr, low, pivot-1);
// 右分区排序
quickSort(arr, pivot+1, high);
}
return;
}
public static <T extends Number & Comparable<T>> T[] bubbleSort(T[] arr){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length-i-1;j++){
if(arr[j].compareTo(arr[j+1]) == 1){
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
}
package com.patterns.strategy3;
import java.util.Arrays;
public class Utils {
public static void main(String [] args){
Long [] arrL = {10L,9L, 8L,7L, 6L, 5L, 4L,3L};
System.out.println(Arrays.toString(arrL));
// bubbleSort(arrL);
// selectSort(arrL);
// insertSort((arrL));
shellSort(arrL);
// quickSort(arrL);
System.out.println(Arrays.toString(arrL));
}
public static <T extends Number & Comparable> void swap(T[] arr, int i, int j){
T temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
public static <T extends Number & Comparable<? super T>> T[] bubbleSort(T[] arr){
for(int i=0; i<arr.length; i++){
for(int j=0; j<arr.length -i -1; j++){
if(arr[j].compareTo(arr[j+1]) == 1){
swap(arr, j, j+1);
}
}
}
return arr;
}
public static <T extends Number & Comparable<? super T>> T[] selectSort(T[] arr){
for(int i=0; i<arr.length; i++){
for(int j=i+1; j<arr.length; j++){
if(arr[i].compareTo(arr[j]) == 1){
swap(arr, i, j);
}
}
}
return arr;
}
public static <T extends Number & Comparable<? super T>> T[] insertSort(T[] arr){
for(int i=0; i<arr.length; i++){
for(int j=i; j>0; j--){
if(arr[j].compareTo(arr[j-1]) == -1){
swap(arr, j, j-1);
}
}
}
return arr;
}
// 改进版的 插入排序
public static <T extends Number & Comparable<? super T>> T[] shellSort(T[] arr){
int h = 1;
while(h < arr.length){
h = 3*h + 1;
}
for(int gap=h;gap>0;gap=(gap-1)/3){ // 从 h 开始缩小间隔=》 gap: 1
for(int i=gap; i<arr.length; i++){ // gap , gap+1, gap+2...
for(int j=i; j-gap>=0; j-=gap){
if(arr[j].compareTo(arr[j-gap]) == -1){
swap(arr, j , j-gap);
}
}
}
}
return arr;
}
public static <T extends Number & Comparable<? super T>> int partition(T[] arr, int low, int high){
T pivot = arr[low];
while(low<high){
while(low<high && arr[high].compareTo(pivot) == 1){
--high;
}
arr[low] = arr[high];
while(low < high && arr[low].compareTo(pivot) == -1){
++low;
}
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
// 快速排序
public static <T extends Number & Comparable<? super T>> T[] quickSort(T[] arr){
return quickSort(arr, 0, arr.length - 1);
}
public static <T extends Number & Comparable<? super T>> T[] quickSort(T [] arr, int low, int high){
if(low < high){
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot -1 );
quickSort(arr, pivot + 1, high);
}
return arr;
}
}
golang Utils.go*
package main
import "fmt"
type Utils struct{}
func main(){
var arr = []int{10,9,8,7,6,5,4,3,2,1}
fmt.Printf("arr before sort: %v\n", arr)
var u = Utils{}
//u.BubbleSort(arr)
//u.SelectSort(arr)
//u.InsertSort(arr)
u.QuickSort(arr, 0, len(arr) -1)
fmt.Printf("arr after sort: %v\n", arr)
}
// 冒泡排序
func(u *Utils) BubbleSort(arr []int) []int{
arrLen := len(arr)
for i:=0; i<arrLen;i++{
for j:=0; j<arrLen-i-1; j++{
if arr[j] > arr[j+1]{
swap(arr, j, j+1)
}
}
}
return arr
}
// 选择排序
func(u *Utils)SelectSort(arr []int) []int{
arrLen := len(arr)
for i:=0; i<arrLen; i++{
for j:=i+1; j<arrLen; j++{
if arr[i] > arr[j]{
swap(arr, i, j)
}
}
}
return arr
}
// 插入排序
func(u *Utils)InsertSort(arr []int){
var arrLen = len(arr)
for i:=0; i<arrLen; i++{
for j:=i; j>0; j--{
if arr[j] < arr[j-1]{
swap(arr, j, j-1)
}
}
}
}
//快排 分区 挖坑填坑大法
func partition(arr[] int, low, high int) int{
// 以最左边为基准值
pivot := arr[low]
for ;low<high;{
for low < high && arr[high] > pivot{
high--
}
arr[low] = arr[high]
for low < high && arr[low] < pivot{
low++
}
arr[high] = arr[low]
}
arr[low] = pivot
return low
}
func(u *Utils)QuickSort(arr[] int, low, high int){
if(low < high){
pivot := partition(arr, low, high)
var u = Utils{}
u.QuickSort(arr, low, pivot -1)
u.QuickSort(arr, pivot + 1, high)
}
}
func swap(arr [] int, i, j int){
arr[i], arr[j] = arr[j], arr[i]
}
scala
import Array.range
object Utils{
def main(arg:Array[String]):Unit={
var arr = Array(10,9,8,7,6,5,4,3,2,1)
show(arr)
//selectSort(arr)
//bubbleSort(arr)
//insertSort(arr)
quickSort(arr, 0, arr.length -1)
println()
show(arr)
}
def swap(arr : Array[Int], i:Int, j:Int):Unit={
arr(i) = arr(i) ^ arr(j)
arr(j) = arr(i) ^ arr(j)
arr(i) = arr(i) ^ arr(j)
}
def bubbleSort(arr:Array[Int]){
for(i <- 0 to arr.length-1; j <- 0 until arr.length - i -1){
if(arr(j) > arr(j+1)){
swap(arr, j, j+1)
}
}
}
def selectSort(arr:Array[Int]):Unit={
var arrLen = arr.length
for(i <- range(0, arrLen, 1)){
for(j <- range(i+1, arrLen, 1)){
if(arr(i) > arr(j)){
swap(arr, i, j)
}
}
}
}
def insertSort(arr:Array[Int]){
for(i <- 0 to (arr.length -1); j <- range(i, 0, -1)){
if(arr(j) < arr(j-1)){
swap(arr, j, j-1)
}
}
}
// 快速排序
def partition(arr: Array[Int], low:Int, high:Int):Int={
var pivot = arr(low)
var left = low
var right = high
while(left < right){
while(left < right && arr(right) > pivot){
right=right-1
}
arr(left) = arr(right)
while(left < right && arr(left) < pivot){
left=left+1
}
arr(right) = arr(left)
}
arr(left) = pivot
return left
}
def quickSort(arr:Array[Int], low:Int, high:Int){
if(low < high){
var pivot = partition(arr, low, high)
quickSort(arr, low, pivot - 1)
quickSort(arr, pivot+1, high)
}
}
def show(arr : Array[Int]){
for(x <- arr){
print(x+",")
}
}
}
package com.ghc.algorithm
object Sorter extends App {
implicit val prefix = "排序算法:"
val arr:Array[Int] = (10 to 1 by -1).toArray
def bubbleSort(arr:Array[Int], name:String="冒泡排序"): Unit ={
println(s"$prefix $name 开始了...")
for(i <- 0 until arr.length; j<-0 until arr.length-i-1){
if(arr(j) > arr(j+1)){
swap(arr, j, j+1)
}
}
println(s"$prefix $name 结束了...")
}
def selectSort(arr:Array[Int], name:String="选择排序"): Unit ={
println(s"$prefix $name 开始了...")
for(i <- 0 to arr.length -2; j<- i+1 to arr.length-1){
if(arr(i) > arr(j)) swap(arr, i, j)
}
println(s"$prefix $name 结束了...")
}
/**
* 堆排序, 构建大顶堆,然后交换首尾下标 对应的值
* @param arr
* @param name
*/
def heapSort(arr:Array[Int], name:String="改进版选择排序 => 堆排序"):Unit={
println(s"$prefix $name 开始了...")
for(dynamicMaxLength<-arr.length to 2 by -1){
heapify(arr, dynamicMaxLength)
swap(arr, 0, dynamicMaxLength-1)
}
println(s"$prefix $name 结束了...")
}
/**
* 功能单一,仅为构建大顶堆
* @param arr
* @param dynamicMaxLength
*/
def heapify(arr:Array[Int], dynamicMaxLength:Int): Unit ={
// 从最后 最右 一个非叶子节点 开始构建大顶堆或者小顶堆
for(p <- (dynamicMaxLength/2 - 1) to 0 by -1){
// 如果 p 存在右子节点
if((2 * p + 2) < dynamicMaxLength){
if(arr(2*p+1) < arr(2*p+2)) swap(arr, 2*p+1, 2*p+2)
}
if(arr(2*p+1) > arr(p)) swap(arr, p, 2*p+1)
}
}
def insertSort(arr:Array[Int], name:String="插入排序"):Unit ={
println(s"$prefix $name 开始了...")
for(i<- 0 to arr.length-1;j<-i to 1 by -1){
if(arr(j) < arr(j-1)) swap(arr, j, j-1)
}
println(s"$prefix $name 结束了...")
}
/**
* 改进版的插入排序, gap 由大到小, 3*h+1 的公式
* @param arr
* @param name
*/
def shellSort(arr:Array[Int], name:String="改进版插入排序 => 希尔排序"):Unit={
println(s"$prefix $name 开始了...")
var h = 1
while(h<=arr.length/3){
h = h*3 + 1
}
var gap = h
while(gap >= 1){
for(i <- gap to arr.length-1; j<- i to gap by -gap){
if(arr(j) < arr(j-gap))
swap(arr, j, j-gap)
}
gap = (gap-1)/3
}
println(s"$prefix $name 结束了...")
}
def quickSort(arr:Array[Int], name:String="快速排序"): Unit ={
println(s"$prefix $name 开始了...")
quickSort(arr, 0, arr.length-1)
println(s"$prefix $name 结束了...")
}
def quickSort(arr:Array[Int], left:Int, right:Int): Unit ={
if(left < right) {
val pivot = partition(arr, left, right)
quickSort(arr, left, pivot-1)
quickSort(arr, pivot+1, right)
}
}
def partition(arr:Array[Int], low:Int, high:Int): Int ={
val pivot = arr(low)
var left = low
var right = high
while(left < right){
while(left < right && arr(right) > pivot){
right -= 1
}
arr(left) = arr(right)
while(left < right && arr(left) < pivot){
left += 1
}
arr(right) = arr(left)
}
arr(left) = pivot
left
}
def mergeSort(arr:Array[Int], name:String="归并排序"): Unit ={
println(s"$prefix $name 开始了...")
mergeSort(arr, 0, arr.length-1)
println(s"$prefix $name 结束了...")
}
/**
* 原理是 左右两边先有序,然后合并, 快排则是 找中分轴然后分治
* @param arr
* @param left
* @param right
*/
def mergeSort(arr:Array[Int], left:Int, right:Int): Unit ={
if(left < right){
val mid = left + ((right - left) /2)
mergeSort(arr, left, mid)
mergeSort(arr, mid+1, right)
merge(arr, left, mid+1, right)
}
}
def merge(arr:Array[Int], left:Int, right:Int, rightBounds:Int): Unit ={
var i = left
var j = right
val mid = right-1
var k = 0
// println(s"$left |$mid| $rightBounds")
var count = (rightBounds - left +1)
// print(s"count: $count")
val temp:Array[Int] = new Array[Int](count)
while (i <= mid && j <= rightBounds) {
// println(s"${arr(i)} <= ${arr(j)} : ${arr(i) <= arr(j)}")
arr(i) <= arr(j) match {
case true => {
temp(k) = arr(i)
k += 1
i += 1
}
case false => {
temp(k) = arr(j)
k += 1
j += 1
}
}
}
while (i <= mid) {
temp(k) = arr(i)
k += 1
i += 1
}
while (j <= rightBounds) {
temp(k) = arr(j)
k += 1
j += 1
}
for (m <- 0 to temp.length - 1) {
arr(left + m) = temp(m)
}
}
def countSort(arr:Array[Int], name:String="计数排序 --》 感觉好傻的亚子"): Unit ={
println(s"$prefix $name 开始了...")
val count = new Array[Int](arr.max+1)
val result = new Array[Int](arr.length)
for(i <- 0 to arr.length-1){
count(arr(i))+=1
}
var m = 0
for(j <- 0 to count.length-1){
if(count(j) > 0){
for(k <- count(j) until 0 by -1){
result(m) = j
m+=1
}
}
}
for(i <- 0 to arr.length-1){
arr(i) = result(i)
}
println(s"$prefix $name 结束了...")
}
def swap(arr:Array[Int], i:Int, j:Int): Unit ={
arr(i) = arr(i) ^ arr(j)
arr(j) = arr(i) ^ arr(j)
arr(i) = arr(i) ^ arr(j)
}
def showArr(arr:Array[Int]):Unit={
println(arr.mkString("<",",",">"))
}
showArr(arr)
bubbleSort(arr)
selectSort(arr)
insertSort(arr)
shellSort(arr)
quickSort(arr)
heapSort(arr)
mergeSort(arr)
countSort(arr)
showArr(arr)
}
import Array.range
object Demo{
def main(args:Array[String]):Unit={
for(i <- range(1,10,1)){
println(i+"! = "+factorial2(n=i))
}
printLangs("golang", "java", "python", "scala")
val result = apply(layout, 10)
println(result)
println(inc(7)-1)
println("1+3 = "+add(1)(3))
}
// 可变参数
def printLangs(langs:String*):Unit={
for(lang <- langs){
println(lang);
}
}
// 函数递归
def factorial(n:BigInt, prod:BigInt=1):BigInt={
if(n<1){
return prod
}
return factorial(n-1, n*prod)
}
// 函数嵌套 阶乘
def factorial2(n:BigInt):BigInt = {
def fact(n:BigInt, accumulator:BigInt):BigInt={
if(n<=1) return accumulator
return fact(n-1, n*accumulator)
}
return fact(n, 1)
}
// 高阶函数
def apply(f: Int => String, v:Int) = f(v)
def layout(n:Int):String = {
return "["+n+"]"
}
// 匿名函数
var inc = (x:Int) => x+1
// 柯里化
def add(x:Int) = (y:Int) => x+y
}
import scala.util.control.Breaks
object Test {
def main(args: Array[String]):Unit={
var arr = Array(10,9,7,5,4,3,2,1)
show(arr)
println()
// bubbleSort(arr)
// selectSort(arr)
// insertSort(arr)
// quickSort(arr)
shellSort(arr)
show(arr)
}
def show:Array[Int] => Unit = (arr) =>{
for(e <- arr){
print(e+",")
}
}
val swap:(Array[Int], Int, Int) => Unit = (arr, i, j) =>{
arr(i) = arr(i) ^ arr(j)
arr(j) = arr(i) ^ arr(j)
arr(i) = arr(i) ^ arr(j)
}
def bubbleSort(ints: Array[Int]):Unit={
var arrLen = ints.length;
for(i <- 0 until arrLen; j <- 0 until (arrLen -i -1)){
if(ints(j) > ints(j+1)){
swap(ints, j, j+1)
}
}
}
def selectSort(arr:Array[Int]):Unit={
for(i <- 0 to arr.length-1; j <- i to arr.length-1){
if(arr(i) > arr(j)){
swap(arr, i, j)
}
}
}
def insertSort(arr:Array[Int]):Unit={
for(i <- 0 until arr.length; j<- Range(i, 0, -1)){
if(arr(j-1) > arr(j)){
swap(arr, j, j-1)
}
}
}
def shellSort(arr:Array[Int]):Unit={
var h = 1
while(h < arr.length/3){
h = h*3 + 1
}
var gap = h
var loop = new Breaks
while(gap > 0){
// loop.breakable(
// if(gap == 0) {
// gap = 1
for(i <- Range(gap, arr.length, 1); j<- Range(i, gap-1, -gap)){
if(arr(j) < arr(j-gap)){
swap(arr, j, j-gap)
}
}
// loop.break()
// }
// )
// show(arr)
// println("gap: "+gap)
gap = (gap -1)/3
}
}
def partition(arr:Array[Int], low:Int, high:Int):Int ={
var left = low
var right = high
var pivot = arr(left)
while(left < right){
while(left < high && arr(right) > pivot){
right -= 1
}
arr(left) = arr(right)
while(left<high && arr(left) < pivot){
left += 1
}
arr(right) = arr(left)
}
arr(left) = pivot
left
}
def quickSort(ints: Array[Int]): Unit ={
quickSort(ints, 0, ints.length -1)
}
def quickSort(arr:Array[Int], low:Int, high:Int): Unit ={
if(low < high){
val pivot = partition(arr, low, high)
quickSort(arr, low, pivot -1)
quickSort(arr, pivot +1, high)
}
}
}
无力吐槽的 shell 正常人谁这么干呐
#!/bin/sh
arr=(10 9 8 7 6 5 4 3 2 1)
len=${#arr[*]}
for((i=0;i<len;i++)) #冒泡排序算法…注意:for语句后面跟“双圆括号”
do
for((j=0;j<len-i-1;j++))
do
t=$[$j+1] #为了改进程序的可读性,使用变量t 来表示"arr(j+1)元素"
if [[ ${arr[$j]} -gt ${arr[$t]} ]] #双方括号表示条件运算 与其中的表达式之间必须有空格,-gt表示大于
#if [[ ${arr[$j]} -gt ${arr[$[$j+1]} ]] #这是 不使用变量t的写法,"arr(j+1)元素"有点不直观
了
then
term=${arr[$j]}
arr[$j]=${arr[$t]}
arr[$t]=$term
fi
done
done
for x in ${arr[@]}
do
echo $x
done
#!/bin/sh
function main(){
showArr $1
breakRows 10
bubbleSort $1
echo $?
echo
showArr $?
}
function breakRows(){
for i in `seq 0 $i`
do
echo
done
}
function bubbleSort(){
arr=$1
len=${#arr[*]}
for i in `seq 0 ${len-1}`;
do
for j in `seq 0 ${len-2-i}`
do
if [[ ${arr[$j]} -gt ${arr[$j+1]} ]]
then
# t=$[$j+1]
tmp=${arr[$j]}
arr[$j]=${arr[$[$j+1]]}
arr[$j+1]=$tmp
fi
done
done
return $arr
}
function showArr(){
arr=$1
for e in ${arr[*]}
do
echo $e
done
}
arr=(10 9 8 7 6 5 4 3 2 1)
main $arr
----------------
#!/bin/sh
for i in `seq 1 9`
do
for j in `seq 1 $i`
do
echo -ne "$i * $j = $[$i * $j]\t"
done
echo ""
done
# 结尾, python 最好不写分号
def bubbleSort(arr):
arr_len = len(arr)
for i in range(0, arr_len, 1):
for j in range(0, arr_len-1-i,1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
def selectSort(arr):
arr_len = len(arr)
for i in range(0, arr_len, 1):
for j in range(i+1, arr_len, 1):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
def inserSort(arr):
arr_len = len(arr)
for i in range(0, arr_len, 1):
for j in range(i, 0, -1):
if arr[j] < arr[j-1]:
arr[j], arr[j-1] = arr[j-1], arr[j]
def shellSort(arr):
h = 1
arr_len = len(arr)
while True:
if h>arr_len:
break
h = h*3 + 1
gap = int(h)
while gap > 0:
for i in range(gap, arr_len, 1):
for j in range(i, gap-1, -gap):
if arr[j] < arr[j-gap]:
arr[j], arr[j-gap] = arr[j-gap], arr[j]
gap = int((gap -1) /3)
# 分区函数
def partition(arr, low, high):
pivot = arr[low]
while low < high:
while low < high and arr[high] > pivot:
high -= 1
arr[low] = arr[high]
while low < high and arr[low] <= pivot:
low += 1
arr[high] = arr[low]
arr[low] = pivot
# print(arr)
return low
# 快排
def quickSort(arr, low, high):
low = 0 if low == None else low
high = (high, len(arr) - 1)[high == None] # 小中 False True
if low < high:
pivot = partition(arr, low, high)
quickSort(arr, low, pivot - 1)
quickSort(arr, pivot+1, high)
return arr
if __name__ == "__main__":
arr = [10,9,8,7,6,5,4,3,2,1]
print(arr)
# bubbleSort(arr)
# selectSort(arr)
# inserSort(arr)
# shellSort(arr)
quickSort(arr, 0, len(arr) - 1)
print(arr)
// golang 结尾 最好不写分号
package main
import "fmt"
func main() {
fmt.Printf("%s\n", "hello world")
arr := []int{10,9,8,7,6,5,4,3,2,1}
fmt.Printf("before sort: %v\n", arr)
fmt.Printf("after sort: %v ",BubbleSort(arr))
}
func BubbleSort(arr []int) []int{
arrLen := len(arr)
for i:=0; i<arrLen;i++{
for j:=0; j<arrLen-1-i;j++{
if arr[j] > arr[j+1]{
arr[j], arr[j+1] = arr[j+1], arr[j]
}
}
}
return arr
}
//scala 结尾最好不写分号
object{
def main(args:Array[String]):Unit={
println("hello world的!!")
}
}
// java , javascript 结尾写分号
提升 shell 颜值
#!/bin/bash
#author Frank
#date 2020/07/26
#functionality: 用于熟悉 shell 指令
:<<EOF
排序算法 shell 版本
EOF
# :noh 取消由于 # 引起的 恶心高亮
#定义颜色变量
RED='\E[1;31m' # 红
GREEN='\E[1;32m' # 绿
YELLOW='\E[1;33m' # 黄
BLUE='\E[1;34m' # 蓝
PINK='\E[1;35m' # 粉红
RES='\E[0m' # 清除颜色
echo -e "${RED} 本脚本用来做排序算法展示 ${RES}"
# main 函数作为脚本入口
function main(){
arr=$1
origin_arr=$1
echo -e "${GREEN} 排序前: ${arr[*]} ${RES}"
while true
do
echo -e "
${YELLOW} 1) 冒泡排序 ${RES}
${GREEN} 2)选择排序 ${RES}
${PINK} 3) 插入排序 ${PINK}
${BLUE} 4) 希尔排序 ${RES}
${RED} x) 将在未来支持更多排序算法... ${RES}
${YELLOW} hints: qu it|QUIT|Quit|q|Q to exit ${RES}"
echo ""
read -p "请输入数字选择对应的排序算法:" num
arr=(10 9 8 7 6 5 4 3 2 1) #$origin_arr
case $num in
1) bubbleSort $arr;;
2) selectSort $arr;;
3) insertSort $arr;;
4) shellSort $arr;;
[qQ]) break;; # 此处跳出的是 while 循环,否则 在 case 里没有意义
quit|QUIT|Quit) break;; # 此处跳出的是 while 循环,否则 在 case 里没有意义
*) clear && echo -e "${RED} 将在未来支持更多算法...敬请等待... ${RES}"
continue;;
esac
echo -e "${BLUE} 排序后 arr: ${arr[@]} ${RES}"
done
#bubbleSort $arr
#selectSort ${arr}
#echo -e "${BLUE} after sort arr: ${arr[@]} ${RES}"
}
function swapArr(){
arr=$1
m=$2
n=$3
tmp=${arr[m]}
arr[m]=${arr[n]}
arr[n]=$tmp
}
# 冒泡排序
function bubbleSort(){
arr=$1
arrLen=${#arr[@]}
for i in `seq 0 ${arrLen-1}`
do
for j in `seq 0 ${arrLen-i-1}`
do
if [[ ${arr[j]} -gt ${arr[j+1]} ]]
then
swapArr $arr $i $j
#tmp=${arr[j]}
#arr[j]=${arr[j+1]}
#arr[j+1]=$tmp
fi
done
done
#echo -e "${PINK} arr: ${arr[@]} ${RES}"
return $arr
}
#选择排序
function selectSort(){
arr=$1
arrLen=${#arr[*]}
for((i=0;i<${arrLen};i++))
do
for((j=i+1;j<${arrLen};j++))
do
if test $[arr[i]] -gt $[arr[j]]
then
swapArr $arr ${i} ${j}
fi
done
done
}
# 插入排序
function insertSort(){
arr=$1
arrLen=${#arr[*]}
for((i=0;i<arrLen;i++))
do
for((j=i;j>0;j--))
do
if [[ ${arr[j]} -lt ${arr[j-1]} ]]
then
echo " ${arr[*]} -> arr[j]: ${arr[j]} , arr[j-1]: ${arr[j-1]}"
tmp=${arr[j]}
arr[j]=${arr[j-1]}
arr[j-1]=$tmp
#echo "${j} --> ${j-1}"
#swapArr ${arr[*]} $j ${j-1}
fi
done
done
}
# shell 排序
function shellSort(){
h=0
arr=$1
arrLen=${#arr[*]}
while [[ h -lt $[$arrLen/3] ]]
do
h=$[$h*3 + 1]
done
gap=h
while [[ gap -gt 0 ]]
do
#gap=$[($gap-1)/3]
for((i=gap;i<arrLen;i++))
do
for((j=i;j>gap-1;j=j-gap))
do
if [[ ${arr[j]} -lt ${arr[j-gap]} ]]
then
echo " ${arr[*]} -> arr[j]: ${arr[j]} , arr[j-gap]: ${arr[j-gap]}"
tmp=${arr[j]}
arr[j]=${arr[j-gap]}
arr[j-gap]=$tmp
fi
done
done
gap=$[($gap-1)/3]
done
}
# 快速排序
#function partition(){}
#function quickSort(){}
arr=(10 9 8 7 6 5 4 3 2 1)
main $arr
java 改进版本
package com.ghc.utils;
import java.util.Arrays;
import java.util.Random;
public class SortAlgorithm {
public static void main(String[] args) {
Integer [] array = randomArray(20);
System.out.println("排序前: " + Arrays.toString(array));
// quickSort(array);
// mergeSort(array);
heapSort(array);
// shellSort(array);
// bubbleSort(array);
// selectSort(array);
// insertSort(array);
System.out.println("排序后: "+ Arrays.toString(array));
loopCheck(array, 1000);
}
public static void loopCheck(Integer[] array, int times){
boolean flag = true;
for(int i=0; i<times; i++) {
Integer[] arrayCopy = new Integer[array.length];
System.arraycopy(array, 0, arrayCopy, 0, array.length);
Arrays.sort(arrayCopy);
flag = checkArrayEquals(array, arrayCopy);
if (!flag) {
System.out.println("not equal!");
break;
}
}
System.out.println("equals: "+ flag);
}
public static Integer[] randomArray(int len){
Integer [] array = new Integer[len];
Random random = new Random();
for(int i=0; i<len; i++){
array[i] = random.nextInt(50);
}
return array;
}
public static <T extends Number & Comparable<T>> boolean checkArrayEquals(T[] array, T[] array2){
boolean flag = true;
for(int i=0; i<array.length; i++){
if(array[i].compareTo(array2[i]) != 0) {
flag = false;
break;
}
}
return flag;
}
public static <T extends Number & Comparable<T>> void quickSort(T[] array){
quickSort(array, 0, array.length - 1);
}
public static <T extends Number & Comparable<T>> void quickSort(T[] array, int left, int right){
if(left < right){
int pivot = partition(array, left, right);
quickSort(array, left, pivot - 1);
quickSort(array, pivot + 1, right);
}
}
public static <T extends Number & Comparable<T>> int partition(T[] array, int left, int right){
T pivot = array[left];
while(left < right){
while(left < right && array[right].compareTo(pivot) >= 0){
right --;
}
array[left] = array[right];
while(left < right && array[left].compareTo(pivot) == -1){
left ++;
}
array[right] = array[left];
}
array[left] = pivot;
return left;
}
public static <T extends Number & Comparable<T>> void heapSort(T[] array){
for(int i=array.length - 1;i>0; i--){
maxHeap(array, i);
swap(array, 0, i);
}
}
public static <T extends Number & Comparable<T>> void maxHeap(T[] array, int endPtr){
int lastPar = endPtr % 2 !=0 ? endPtr >> 1: (endPtr >> 1) -1;
for(int i=lastPar; i>=0; i--){
if(2*i+2 <= endPtr && array[2*i+2].compareTo(array[i]) == 1){
swap(array, i, 2*i+2);
}
if(array[2*i+1].compareTo(array[i]) == 1){
swap(array, i, 2*i+1);
}
}
}
public static <T extends Number & Comparable<T>> void swap(T[] array, int i, int j){
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static <T extends Number & Comparable<T>> void mergeSort(T[] array){
mergeSort(array, 0, array.length - 1);
}
public static <T extends Number & Comparable<T>> void mergeSort(T[] array, int left, int right){
if(left < right){
int mid = left + ((right - left) >> 1);
mergeSort(array, left, mid);
mergeSort(array, mid+1, right);
merge(array, left, mid+1, right);
}
}
public static <T extends Number & Comparable<T>> void merge(T[] array, int left, int right, int rightBounds){
int i = left;
int j = right;
int mid = right - 1;
int k = 0;
int count = rightBounds - left + 1;
T[] temp = Arrays.copyOf(array, count);
while(i <= mid && j <= rightBounds){
temp[k++] = array[i].compareTo(array[j]) <= 0 ? array[i++]:array[j++];
}
while(i <= mid){
temp[k++] = array[i++];
}
while(j <= rightBounds){
temp[k++] = array[j++];
}
for(int m=0; m<count; m++){
array[left+m] = temp[m];
}
}
public static <T extends Number & Comparable<T>> void shellSort(T[] array){
int h = 1;
while(h < array.length / 3){
h = 3*h + 1;
}
for(int gap=h; gap >= 1; gap=(gap-1)/3){
for(int i=0; i<array.length; i++){
for(int j=i; j-gap >= 0; j-=gap){
if(array[j-gap].compareTo(array[j]) == 1){
swap(array, j-gap, j);
}
}
}
}
}
public static <T extends Number & Comparable<T>> void bubbleSort(T[] array){
for(int i=0; i<array.length;i++){
for(int j=0; j<array.length - i - 1;j++){
if(array[j].compareTo(array[j+1]) == 1){
swap(array, j, j+1);
}
}
}
}
public static <T extends Number & Comparable<T>> void selectSort(T[] array){
for(int i=0; i<array.length-1; i++){
for(int j=i+1; j<array.length; j++){
if(array[i].compareTo(array[j]) == 1){
swap(array, i, j);
}
}
}
}
public static <T extends Number & Comparable<T>> void insertSort(T[] array){
for(int i=0; i<array.length; i++){
for(int j=i; j-1>=0; j--){
if(array[j-1].compareTo(array[j]) == 1){
swap(array, j-1, j);
}
}
}
}
}
如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。