Merge sort

Thought:

Merge-sort is an effective sorting algorithm based on MERGE operation. It is a typical application of Divide and Conquer. The ordered subsequences are combined to obtain a fully ordered sequence. That is, each subsequence is ordered first, and then the subsequence segments are ordered. If two ordered tables are merged into one ordered table, it is called binary merge. Merge sort is a stable sorting method. — Baidu Encyclopedia

Time complexity: O(nlogn)

Stability: stability

Go language implementation

Partition rules

func mergeSort(arr []int,left int,right int){
    ifMergeSort (arr,mid+1,right) // mergeSort(arr,mid+1,right) // mergeSort(arr,mid+1,right) // mergeSort(arr,mid+1,right) // mergeSort(arr,mid+1,right) // mergeSort(arr,mid+1,right) // mergeSort(arr,mid+1,right) // mergeSort merge(arr,left,mid,right) } }Copy the code

Merging rules

Func merge(arr []int,left int,mid int,right int){var temp = make([]int,len(arr)) Var pointer2 = mid+1 var pointer2 = mid+1 var loc = left // Used to record the current pointer to a temporary arrayforPointer1 <=mid && pointer2<=right{// iterate over the left and right arraysifArr [pointer1] < arr[pointer2] {// Smaller elements enter temp first [loc] = arr[pointer1] pointer1++ // left array points to the next bit}else{temp[loc] = arr[pointer2] pointer2++} locc ++ But the left and right tail elements are still not inserted, so I have to insert them againforTemp [loc] = arr[pointer1] loc++ pointer1++}forTemp [loc] = arr[pointer2] loc++ pointer2++} temp[loc] = arr[pointer2] loc++ pointer2++} temp[loc] = arr[pointer2] loc++ pointer2++fori:=left; i<=right; i++{ arr[i]=temp[i] } }Copy the code

/ / test

func main() {
	var data = []int{3, 5, 75, 34, 8, 31, 44, 76, 87, 25, 73, 11}
	mergeSort(data, 0, len(data)-1)
	fmt.Println(data) //[3 5 8 11 25 31 34 44 73 75 76 87]
}
Copy the code

conclusion

Merge sort is the use of partition thought, its core is to need to sort an array of points according to certain rules, when no longer points assigned to the left and right sides, comparing the array elements with small row in front of big row behind (or big row at the front of the small row behind) the way of merging into an array, an orderly