[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/bhnan/algorithm-pattern/master/basic_algorithm/sort.md [Back]  [Original]

# 

## 

### 

```go
func QuickSort(nums []int) []int {
    // 
    quickSort(nums, 0, len(nums)-1)
    return nums

}
// 
func quickSort(nums []int, start, end int) {
    if start < end {
        // divide
        pivot := partition(nums, start, end)
        quickSort(nums, 0, pivot-1)
        quickSort(nums, pivot+1, end)
    }
}
// 
func partition(nums []int, start, end int) int {
    // pivot
    p := nums[end]
    i := start
    // 
    for j := start; j < end; j++ {
        if nums[j] < p {
            swap(nums, i, j)
            i++
        }
    }
    // 
    swap(nums, i, end)
    return i
}
// 
func swap(nums []int, i, j int) {
    t := nums[i]
    nums[i] = nums[j]
    nums[j] = t
}
```

### 

```go
func MergeSort(nums []int) []int {
    return mergeSort(nums)
}
func mergeSort(nums []int) []int {
    if len(nums)  right[r] {
            result = append(result, right[r])
            r++
        } else {
            result = append(result, left[l])
            l++
        }
    }
    // 
    result = append(result, left[l:]...)
    result = append(result, right[r:]...)
    return
}
```

### 

 complete binary tree

>  VS 

![image.png](https://img.fuiboom.com/img/tree_type.png)

[](https://www.bilibili.com/video/av18980178/)

![image.png](https://img.fuiboom.com/img/heap.png)



```go
package main

func HeapSort(a []int) []int {
    // 1a
	// 2a
	for i := len(a)/2 - 1; i >= 0; i-- {
		sink(a, i, len(a))
	}
	// 3a[0]a[len(a)-1]
	// 4
	for i := len(a) - 1; i >= 1; i-- {
		// 
		swap(a, 0, i)
		// 
		sink(a, 0, i)
	}
	return a
}
func sink(a []int, i int, length int) {
	for {
		// (0i*2+1)
		l := i*2 + 1
		// 
		r := i*2 + 2
		// idx
		idx := i
		// 
		if l < length && a[l] > a[idx] {
			idx = l
		}
		// 
		if r < length && a[r] > a[idx] {
			idx = r
		}
		// 
		if idx == i {
			break
		}
		// 
		swap(a, i, idx)
		// idx
		i = idx
	}
}
func swap(a []int, i, j int) {
	a[i], a[j] = a[j], a[i]
}

```

## 

[](https://www.cnblogs.com/onepixel/p/7674659.html)

[](https://labuladong.gitbook.io/algo/shu-ju-jie-gou-xi-lie/er-cha-dui-xiang-jie-shi-xian-you-xian-ji-dui-lie)

## 

- [ ] 

Web Proxy Viewer  |  New URL  |  Original Page